Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of type either float or strings to int type in Julia (Replicating int() from Python)

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!

like image 944
Mohammad Saad Avatar asked Mar 02 '23 16:03

Mohammad Saad


2 Answers

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.

like image 154
Andrej Oskin Avatar answered Mar 04 '23 05:03

Andrej Oskin


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
like image 41
Przemyslaw Szufel Avatar answered Mar 04 '23 05:03

Przemyslaw Szufel