Thursday, 31 March 2016

Julia: Convert string to integer

By using parse method you can convert a string to an integer (or) to any number type.

parse(type, str, [base])

Parse a string as a number, base is optional, by default base=10.
julia> parse(Int64, "123")
123

julia> parse(Int64, "123", 16)
291

julia> parse(Float64, "123.345")
123.345


If the string doesn’t represent valid number, then error is thrown.
julia> parse(Float64, "123.345a")
ERROR: ArgumentError: invalid number format "123.345a" for Float64
 in parse at parse.jl:164

julia> parse(Int64, "123a")
ERROR: ArgumentError: invalid base 10 digit 'a' in "123a"
 in tryparse_internal at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib (repeats 2 times)
 in parse at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib


Previous                                                 Next                                                 Home

No comments:

Post a Comment