Why I can't convert non-integer float to Int64?

Hello, I am new to Julia, I worked in the past mostly in Python and a bit with JAVA, C and C++. My question is that in the code below I get InexactError. The conversion works fine with floats with .0 decimal and not with another decimal ? I found that I have to use floor() or other similar functions before conversion.

v::Float16 = 120.5
Int64(v)

The error:

InexactError: Int64(120.5)

Stacktrace:
 [1] Int64(x::Float16)
   @ Base .\float.jl:912
 [2] top-level scope

The simple answer is that there are many results that you may want when converting the value 120.5 to a decimal and so you need to choose which one you want.

The most obvious choices are round (which has several rounding modes) or ceil/floor

3 Likes

From PEP 20 – The Zen of Python :smile:

Explicit is better than implicit.

3 Likes

Thank you, it make sense yes.

1 Like

Thank you, yes agreed :sweat_smile:

julia> Float16(120.5)                                   
Float16(120.5)

julia> round(Int64, Float16(120.5))                     
120

julia> round(Int64, Float16(120.5), RoundNearest)       
120

julia> round(Int64, Float16(120.5), RoundNearestTiesAway)
121
2 Likes

Thank you.