Parse Float32 string

How can I parse strings like “1.23f-4” to Float32?

julia> parse(Float64, "1.23e-4")

julia> parse(Float32, "1.23f-4")
ERROR: ArgumentError: cannot parse "1.23f-4" as Float32
 [1] _parse_failure(T::Type, s::String, startpos::Int64, endpos::Int64)
   @ Base ./parse.jl:373
 [2] _parse_failure(T::Type, s::String)
   @ Base ./parse.jl:373
 [3] #tryparse_internal#509
   @ ./parse.jl:369 [inlined]
 [4] tryparse_internal
   @ ./parse.jl:366 [inlined]
 [5] #parse#510
   @ ./parse.jl:379 [inlined]
 [6] parse(::Type{Float32}, s::String)
   @ Base ./parse.jl:379
 [7] top-level scope
   @ REPL[87]:1

Did you mean parse(Float32, "1.23e-4")? This works.

1 Like

No. The strings are like “1.23f-4”.

See Parsing Float32 literals and Extracting a float from a string


What does that notation mean by the way? What decimal number corresponds to 1.23f-4?

Edit: Ugh, I was not aware:

julia> 1.23f-4

This comment is informative on why Base.parse doesn’t do what Meta.parse can, I’ll just copy the text too:

In general, parse(T, string) isn’t related to Julia syntax. parse(Int, "1_000") doesn’t work either, even though 1_000 is a valid Julia integer literal, whereas parse(DateTime, "2022-04-26T15:15") works even though 2022-04-26T15:15 is not Julia syntax. What we accept in parse is more about what we’re likely to find in external data sources (e.g. CSV files).


Note that the returned object is a Float32, not a Float64, which is what the OP is asking about - Parsing a Float32 formatted as a string representing as a Float64.

1 Like

There is a related discussion on github, and your issue seemingly still does not work out of the box.
You could use, e.g., package Parsers.jl which does the job.

julia> x = Parsers.parse(Float32, "1.23f-4")

1 Like

Out of curiosity, where are you seeing data (not source code) with this format? It’s nonstandard for e.g. CSV files.

I am filtering log files created by a job running Julia code. Float32 is used for Flux. @stevengj Thanks for quick response.