在长生不老药中舍入浮点数的最佳方法是什么

What is the best way to round a float in elixir

我正在尝试将长生不老药中的 Float 舍入到小数点后两位。

如果我有数字 12.555,我希望我的舍入函数为 return 12.56

我本来以为 Float.round 是我想要的,但这个功能并不总是 return 我想要的答案。

例如...

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

我知道我可以用一个临时函数来完成这个,但我认为一定有更好的解决方案。

我目前的解决方案是...

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

这样就可以了,但就像我说的,我只是想知道是否有更好的解决方案。

提前致谢

由于浮点数的工作方式,如果你想要精度,包括控制 rounding algorithms, you need to use a library such as Decimal:

12.555
|> Decimal.from_float()
|> Decimal.round(2)

输出:

#Decimal<12.56>

然后您可以使用 Decimal.to_string/2 for printing or Decimal.to_float/1 等函数,但请注意 to_float/1 也是一个不精确的操作,可能会失败。

如果您不想使用库,

Float.ceil/2 可能会帮助您解决这个问题

iex> 12.555 |> Float.ceil(2)        
12.56