Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a string to a float or int in Julia?

Tags:

julia

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.

like image 973
logankilpatrick Avatar asked Sep 29 '19 02:09

logankilpatrick


People also ask

How to convert string to float or integer in Julia?

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.

How do you parse a string in Julia?

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).

How to parse a string to a float in Java?

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

How do I convert a string to a datatype in Julia?

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.


1 Answers

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

julia> parse(Float64, "1")
1.0
like image 167
Anshul Singhvi Avatar answered Sep 21 '22 13:09

Anshul Singhvi