I am trying to take a string a = "99.99"
and then convert it to be of type float. On top of that, I want to be able to convert a
to an int as well. How can I do that? The built-in int()
and float()
functions don't appear to take strings.
julia> a = "99.99"
"99.99"
julia> float(a)
ERROR: MethodError: no method matching AbstractFloat(::String)
Closest candidates are:
AbstractFloat(::Bool) at float.jl:252
AbstractFloat(::Int8) at float.jl:253
AbstractFloat(::Int16) at float.jl:254
...
Stacktrace:
[1] float(::String) at ./float.jl:271
[2] top-level scope at REPL[2]:1
julia> Int(a)
ERROR: MethodError: no method matching Int64(::String)
Closest candidates are:
Int64(::Union{Bool, Int32, Int64, UInt32, UInt64, UInt8, Int128, Int16, Int8, UInt128, UInt16}) at boot.jl:710
Int64(::Ptr) at boot.jl:720
Int64(::Float32) at float.jl:700
...
Stacktrace:
[1] top-level scope at REPL[3]:1
Inspired by this post.
For that, it gave us the parse method to achieve this. We can use the parse method to convert a string into float or integer in Julia. We can also specify the base for conversion like hexadecimal, octal, binary, or decimal.
The string input and required base are taken from the user using the readline () method of Julia. The parse () method converts the base into Integer (Int64). Next, the parse () method is used to convert the String into Integer datatype with the given base (here hexadecimal).
Alternatively, you can use the Float.parseFloat () method to parse a string to a float. To get the integer value, cast the resultant float value as discussed before. 3. Using Integer.parseInt () method
Julia allows type conversion for compatible datatypes. Julia has an inbuilt parse method that allows conversion of string to numeric datatype. A string can be converted to the desired numeric datatype until it’s an invalid string. We can also specify the base for conversion like decimal, binary, octal or hexadecimal.
You can use the parse(::Type{T}, ::AbstractString)
function, like so:
julia> parse(Float64, "1")
1.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With