Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang float_to_binary truncates decimals strangely

Tags:

erlang

elixir

The Erlang float_to_binary function truncates decimals strangely. For instance, I would expect it to convert 0.45 with no decimal places to "0". Instead we get (example in Elixir):

iex> :erlang.float_to_binary(0.45, [decimals: 0])
"1"
iex> :erlang.float_to_binary(0.445, [decimals: 0])
"1"
> :erlang.float_to_binary(0.444, [decimals: 0])
"0"

Thus, it seems like rounding is being applied iteratively from right to left until the desired number of decimals is reached.

Is this expected behavior? Why doesn't it either round correctly or just truncate? Both of those options seem much more predictable to me.

like image 318
Max Kaplan Avatar asked Nov 16 '25 19:11

Max Kaplan


1 Answers

This was a bug in Erlang which was fixed on Jan 15 2018 and first included in Erlang 20.3. If you upgrade to Erlang 20.3 or later, you should get "0" for 0.445.

like image 174
Dogbert Avatar answered Nov 18 '25 19:11

Dogbert