Julia: Convert numeric string to float or int

38,546

Solution 1

You can parse(Float64,"1") from a string. Or in the case of a vector

map(x->parse(Float64,x),stringvec)

will parse the whole vector.

BTW consider using tryparse(Float64,x) instead of parse. It returns a Nullable{Float64} which is null in the case string doesn't parse well. For example:

isnull(tryparse(Float64,"33.2.1")) == true

And usually one would want a default value in case of a parse error:

strvec = ["1.2","NA","-1e3"]
map(x->(v = tryparse(Float64,x); isnull(v) ? 0.0 : get(v)),strvec)
# gives [1.2,0.0,-1000.0]

Solution 2

Use parse(Float64,"1").

See more at: parse specification

Share:
38,546
peter-b
Author by

peter-b

Software Engineer

Updated on December 06, 2020

Comments

  • peter-b
    peter-b over 3 years

    I am trying to write numeric data pulled from a database into a Float64[]. The original data is in ::ASCIIString format, so trying to push it to the array gives the following error:

    julia> push!(a, "1")
    ERROR: MethodError: `convert` has no method matching convert(::Type{Float64}, ::ASCIIString)
    This may have arisen from a call to the constructor Float64(...),
    since type constructors fall back to convert methods.
    Closest candidates are:
      call{T}(::Type{T}, ::Any)
      convert(::Type{Float64}, ::Int8)
      convert(::Type{Float64}, ::Int16)
      ...
     in push! at array.jl:432
    

    Attempting to convert the data directly unsurprisingly throws the same error:

    julia> convert(Float64, "1")
    ERROR: MethodError: `convert` has no method matching convert(::Type{Float64}, ::ASCIIString)
    This may have arisen from a call to the constructor Float64(...),
    since type constructors fall back to convert methods.
    Closest candidates are:
      call{T}(::Type{T}, ::Any)
      convert(::Type{Float64}, ::Int8)
      convert(::Type{Float64}, ::Int16)
      ...
    

    Given that I know the data is numeric, is there a way I can convert it before pushing?

    p.s. I am using version 0.4.0

  • Reiner Martin
    Reiner Martin over 5 years
    In the meantime (with Julia 1.0 out), the link to use is docs.julialang.org/en/latest/base/numbers/#Base.parse
  • Ricoter
    Ricoter over 3 years
  • Maciek Leks
    Maciek Leks over 3 years
    @Ricote, I've updated the link. Thank you.
  • BallpointBen
    BallpointBen almost 3 years
    Commenting in 2021: what is Nullable{T}? It looks like it should be Union{Nothing,T}? And should isnull be isnothing (or === nothing) now?