To convert a float to an integer in Julia, you can use the trunc
or round
functions. Below are the examples:
Convert float to int in Julia Examples
julia> trunc(3.8) 3 julia> round(3.8) 4
The trunc
function will round the number down to the nearest integer, while the round
function will round up or down to the nearest integer, depending on the decimal value.
You can also use the Int
function to convert a float to an integer. This function will round down to the nearest integer, just like trunc
. Here's an example:
julia> Int(3.8) 3
In general, it's best to use the trunc
or Int
function to convert a float to an integer in Julia, unless you specifically want to round the number up or down.
Here are a few more examples of converting floats to integers in Julia, using the trunc
, round
, and Int
functions:
julia> trunc(-3.8) -3 julia> round(-3.8) -4 julia> Int(-3.8) -3 julia> trunc(3.14159) 3 julia> round(3.14159) 3 julia> Int(3.14159) 3
As you can see, the trunc
and Int
functions will always round down to the nearest integer, while the round
function will round up or down depending on the decimal value.
You can also use these functions on arrays of floats to convert all the values in the array to integers. For example:
julia> a = [3.8, -3.14159, 3.14159, 2.71828] 4-element Array{Float64,1}: 3.8 -3.14159 3.14159 2.71828 julia> trunc.(a) 4-element Array{Int64,1}: 3 -3 3 2 julia> round.(a) 4-element Array{Int64,1}: 4 -3 3 3 julia> Int.(a) 4-element Array{Int64,1}: 3 -3 3 2
As you can see, using the .
after the function name (e.g. trunc.
) applies the function to each element in the array. This is a convenient way to convert multiple floats to integers at once.