Type-safe conversion of strings to numbers

It is easy to convert a string to a Float64:

julia> parse(Float64,"1.23456789")
1.23456789

It is (obviously) not possible to convert a string to an AbstractFloat:

julia> parse(AbstractFloat,"1.23456789")
ERROR: MethodError: no method matching tryparse(::Type{AbstractFloat}, ::String)

Is it possible to convert strings to numbers in a type-safe way?

Use tryparse:

julia> tryparse(Int, "a") === nothing
true

julia> tryparse(Int, "12")
12
3 Likes

For a result that isn’t nothing or an error, you really do need a specific type. If you don’t want to specify a type at all, you could fall back to parsing in the source code sense eval(Meta.parse("1im"), though the evaluation occurs in the global scope (for example, if you do the call in a function, execution moves to the global scope then provides the value to the function).

1 Like

Thanks! So if I use eval(Meta.parse("1.23456789")), then my package will work regardless of whether it is installed on a 32 or 64 bit system? It does seem strange to me that type-safe string conversion is straightforward for Integers (Int is equivalent to Int32 on a 32-bit system), but not for floats. Is there any logical reason for that?

Int is a constant alias for Int32 on 32-bit systems or Int64 on 64-bit systems. Integer is the abstract type for integers, analogous to AbstractFloat for floating points.

I don’t know your use case but you should avoid manually calling the parse-evaluate process, running things in the global scope isn’t cheap. Though if you really are reading in strings with arbitrary Julia code, that might be necessary and it would be unfeasible to try to narrow down types at compile-time.

2 Likes

Okay. In that case the cleanest solution would probably be to define my own constant alias, like this:

julia> const Float = Sys.WORD_SIZE==64 ? Float64 : Float32
julia> parse(Float,"1.23456789")
1.23456789

No, Float64 vs Float32 has nothing to do with the word size, they are unrelated concepts. Just use Float64.

Floating point arithmetic is handled by separate circuits on the processor from integer arithmetic, and even on a machine with a 32-bit address space, specific hardware for 64 bit floating point arithmetic has been standard for decades. 64 bit address spaces are way newer than 64 bit float support (because 32 bit floats are incredibly restrictive).

The only machines old enough to not have native hardware support for Float64 are too ancient to actually compile and run julia code anyways.

5 Likes

There’s no need, decimals or e-notation do Float64 and f-notation does Float32 on both systems. Int and UInt are documented examples of Type Aliases and this is explained:

(Note that unlike Int , Float does not exist as a type alias for a specific sized AbstractFloat. Unlike with integer registers, where the size of Int reflects the size of a native pointer on that machine, the floating point register sizes are specified by the IEEE-754 standard.)

1 Like