Wednesday 30 March 2016

Julia: convert(): convert one type of data to other


convert(T, x)
Convert x to value of type T.
julia> a=123.0
123.0

julia> b=convert(Int64, a)
123

julia> b
123

julia> typeof(b)
Int64


Convert method throws InexactError, if x is not exactly converted to type T.
julia> a=123.34
123.34

julia> b=convert(Int64, a)
ERROR: InexactError()
 in convert at int.jl:209

If convert method don’t know how to convert x to given type T, then it throws MethodError.

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


Previous                                                 Next                                                 Home

No comments:

Post a Comment