Max Kaplan
Max Kaplan

Reputation: 115

Erlang float_to_binary truncates decimals strangely

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.

Upvotes: 4

Views: 1103

Answers (1)

Dogbert
Dogbert

Reputation: 222158

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.

Upvotes: 10

Related Questions