How do I convert an float to an integer in Elixir

To summarize the different answers listed on this question, there are good four options as of writing this: trunc/1, round/1, floor/1, and ceil/1. All accept both floats and integers.

trunc/1

Removes the decimal part of a float.

iex> trunc(2.3)
2
iex> trunc(-2.3)
-2

round/1

Rounds to the nearest integer.

iex> round(2.3)
2
iex> round(2.7)
3
iex> round(-2.3)
-2
iex> round(-2.7)
-3

floor/1

Always rounds down. Available as of Elixir 1.8.0.

iex> floor(2.3)
2
iex> floor(-2.3)
-3

ceil/1

Always rounds up. Available as of Elixir 1.8.0.

iex> ceil(2.3)
3
iex> ceil(-2.3)
-2

Use trunc(2.0) or round(2.0). Those are auto-imported since they are part of Kernel and they are also allowed in guard clauses.


Use trunc(number) function which is a Kernel function and auto-imported.

Elixir Docs of this function:

Returns the integer part of number.


Examples:

trunc(5.4)    -->    5

trunc(-5.99)  -->   -5

trunc(-5)     -->   -5

Tags:

Elixir