'Convert float to int in Julia Lang

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



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Combining the previous answers:

julia> int(x) = floor(Int, x)
int (generic function with 1 method)

julia> int(3.14)
3

julia> int(3.94)
3

Solution 4:[4]

To answer the general question in the title (convert Float to Int), we can do:

round(Int, 1.3)
# 1
round(Int, 1.7)
# 2

Solution 5:[5]

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

Solution 6:[6]

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

Solution 7:[7]

seems that you really need modf instead:

help?> modf
search: modf ComposedFunction mod1 mod module

  modf(x)

  Return a tuple (fpart, ipart) of the
  fractional and integral parts of a number.      
  Both parts have the same sign as the argument.  

  Examples
  ??????????

  julia> modf(3.5)
  (0.5, 3.0)
  
  julia> modf(-3.5)
  (-0.5, -3.0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fengyang Wang
Solution 3 Jabba
Solution 4
Solution 5 Yousef Saber
Solution 6 Javi12
Solution 7 longemen3000