What is the best way to round a float in elixir
Float.ceil/2 might help you with this if you don't want to use a library
iex> 12.555 |> Float.ceil(2)
12.56
Because of the way floating point numbers work, if you want precision, including controlling rounding algorithms, you need to use a library such as Decimal:
12.555
|> Decimal.from_float()
|> Decimal.round(2)
Output:
#Decimal<12.56>
You can then use functions like Decimal.to_string/2
for printing or Decimal.to_float/1
, but beware that to_float/1
is also an imprecise operation and could fail.