7

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.

logankilpatrick
  • 13,148
  • 7
  • 44
  • 125

1 Answers1

7

You can use the parse(::Type{T}, ::AbstractString) function, like so:

julia> parse(Float64, "1")
1.0
Anshul Singhvi
  • 1,692
  • 8
  • 20