Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to round a float in elixir

I am trying to round a Float in elixir to 2 decimal places.

If I have the number 12.555, I would like my rounding function to return 12.56

I originally thought that the Float.round was what I wanted but this function does not always return the answer I would like.

For example...

iex()> Float.round(12.555, 2)
12.55

I know that I can get this done with a makeshift function but I thought that there must be a better solution.

My current solution is...

iex()> round(12.555 * 100) / 100
12.56

This does the job but like I said, I just wanted to know if there was a better solution.

Thanks in advance

like image 736
RobStallion Avatar asked Apr 08 '19 19:04

RobStallion


1 Answers

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
like image 102
BlueGene Avatar answered Sep 22 '22 20:09

BlueGene