去除 Elixir 中不必要的浮点精度的简单方法?

Emi*_*ily 1 elixir

我有 Elixir 计算返回这样的浮点数:

0.15300000000000002
5.140000000000005
0.0033000000000000004
Run Code Online (Sandbox Code Playgroud)

但我只想显示:

0.153
5.14
0.0033
Run Code Online (Sandbox Code Playgroud)

我熟悉使用...

:erlang.float_to_binary
Run Code Online (Sandbox Code Playgroud)

...指定小数精度和舍入选项。问题是我事先不知道精确设置精度的小数位。

有没有简单的方法来做到这一点?

Mik*_*hot 5

由于浮点错误的性质,我认为没有选择精度就没有通用的方法来做到这一点。

可以帮助的:compact选项float_to_binary:

iex(10)> :erlang.float_to_binary(1.0 / 10.0, [{:decimals, 15}, :compact])
"0.1"
iex(11)> :erlang.float_to_binary(1.0 / 10.0, [{:decimals, 30}, :compact])
"0.100000000000000005551115123126"
Run Code Online (Sandbox Code Playgroud)

它将尾随零修剪到您指定的精度。