Convert float to int in Julia Lang
51,770
Solution 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
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
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
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
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
Author by
JJTO
Updated on October 26, 2021Comments
-
JJTO over 2 years
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
-
jjjjjj over 6 yearsAs of v0.6, note that the output of
floor
is not anInt64
type, but rather aFloat64
as per the example:test = ceil(0.2); typeof(test)
-
karatedog almost 6 years
trunc
returns Float now, not Integer. -
Fengyang Wang almost 6 years@karatedog
trunc(x::Float64)
has always returned Float. But if you provideInt
as the first argument, as intrunc(Int, 1.2)
, you will get an integer. -
Yousef Saber about 4 years
floor(Int,x)
is more accurately according to docs -
Olov about 4 yearsIt is recommended to use the alias
Int
instead of explicitly stating the size of the integer, see docs.julialang.org/en/v1/manual/types/#Type-Aliases-1 -
Muppet over 3 yearsI'm sorry, but not why do
round(Int64, 1.3)
instead? It's much more concise? What's the purpose of adding an explicit conversion? -
Hansang almost 2 yearsThis should be the best answer