31
votes

Is there a way to convert a floating number to int in Julia? I'm trying to convert a floating point number to a fixed precision number with the decimal part represented as 8bit integer. In order to do this, I need to truncate just the decimal part of the number and I figured the best way to do this would be to subtract the converted integer of x from floating point x:

  x = 1.23455
y = x - Int(x)
println(y)

y = 0.23455

5
The code you've provided won't work, since Int(x) will return an Inexact error unless x is a whole number expressed as Float64, e.g. 1.0 or -44.0. Also, I can't tell what you're actually after based on the question. Your wording makes it sound like you want the decimal portion of a Float64, expressed as an Int8. Is this right? That is an odd request, particularly given that for your example number 1.23455, the decimal portion as Int64 is 23455, but this is obviously much too large to be expressed as an Int8.Colin T Bowers
Also, seems that you could use the rounding functions. All these functions accept target types for conversion: docs.julialang.org/en/release-0.5/manual/…amrods

5 Answers

33
votes

It is possible that you are looking for trunc. It depends on what you mean by the decimal part. This is the difference between trunc and floor:

julia> trunc(Int, 1.2)
1

julia> trunc(Int, -1.2)
-1

julia> floor(Int, 1.2)
1

julia> floor(Int, -1.2)
-2
14
votes

I think you are looking for floor:

julia> x = 1.23455
1.23455

julia> floor(x)
1.0

julia> y = x - floor(x)
0.23455000000000004
2
votes

To answer the general question in the title (convert Float to Int), I prefer to round, then convert to Int:

convert(Int64, round(1.3, digits=0))
# 1
convert(Int64, round(1.7, digits=0))
# 2
2
votes

according to floor docs you can do that way

julia> x = 45.5
45.5

julia> typeof(x)
Float64

julia> x = floor(Int8,x)
45

julia> typeof(x)
Int8
2
votes

It seems that what you really need is the decimal part of the number. If this is the case, you can use modulo 1 directly like this:

x = 1.23455
y = x % 1
println(y)
# 0.2345