I’m parsing string data from a file written by LabVIEW – numbers written out as strings, which I am parsing to numeric types.
In this example, integers.
The LabVIEW program is a little inconsistent. The pressure settings are always a whole value, but sometimes the LabVIEW program will write out “20” and other times “20.0”
Julia’s built-in parse() will barf on the second one. For example:
input_press = "20"
setpress = parse(Int,input_press)
println("setpress = ",setpress)
input_press = "20.0"
setpress = parse(Int,input_press)
println("setpress = ",setpress)
Results in the output:
setpress = 20
ERROR: ArgumentError: invalid base 10 digit '.' in "20.0"
Stacktrace:
Solution
I can use the Parsers package and it’s tryparse() function, which will return nothing if the conversion fails.
using Parsers
input_press = "20"
setpress = Parsers.tryparse(Int,input_press)
if isnothing(setpress)
floatpress = Parsers.tryparse(Float64,input_press)
setpress = Integer(floatpress)
end
println("setpress = ",setpress)
input_press = "20.0"
setpress = Parsers.tryparse(Int,input_press)
if isnothing(setpress)
floatpress = Parsers.tryparse(Float64,input_press)
setpress = Integer(floatpress)
end
println("setpress = ",setpress)
This works. I could even write it into a small function.
However
This being Julia, is there a more clever way to accomplish this?