I would like to replicate the functionality of python function int()
which can convert either string
or float
to a int
type with base of 10.
Reference: https://www.w3schools.com/python/ref_func_int.asp
I have developed a small code to perform this execution:
a = "5.9"
print("Type of a = ", typeof(a))
if typeof(a) == String
x1 = reinterpret(Int64, a) # 1st attempt
x1 = parse(Int, a) # 2nd attempt
else
x1 = floor(Int64, a)
end
print("\nx1 = $x1", ",\t","type of x1 = ", typeof(x1))
In the above code, I have shown the functions to convert the string to int
type but neither works.
Please do suggest a solution which can convert the string
to int
and also for any recommendation to optimize the above code?
Thanks!
This is a good example to play with multiple dispatch. Instead of comparing type (btw, it's better to write a isa String
instead of typeof(a) == String
), you can define multiple functions with different behavior.
myparse(x::Nothing) = nothing
myparse(x::Integer) = x
myparse(x::Real) = Int(round(x))
myparse(x::AbstractString) = myparse(tryparse(Float64, x))
and this is how it looks in action
julia> myparse(1)
1
julia> myparse(1.0)
1
julia> myparse(1.1)
1
julia> myparse("12.3")
12
julia> myparse("asdsad")
In last case it can't parse string, so it just return nothing
.
Shorter form:
myparse(x::Real) = trunc(Int, x)
myparse(::Nothing) = nothing
myparse(x::AbstractString) = myparse(tryparse(Float64, x))
trunc
drops the floating point and only integer part is left, e.g.:
julia> myparse("-4.7")
-4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With