elixir
elixir copied to clipboard
:erlang.trunc/1 not working properly
iex(1)> trunc(222222222222222300.0)
222222222222222304
iex(2)> trunc(2222222222222222300.0)
2222222222222222336
iex(3)> trunc(22222222222222222300.0)
22222222222222221312
iex(4)> trunc(222222222222222222300.0)
222222222222222229504
iex(5)> trunc(2222222222222222222300.0)
2222222222222222163968
iex(6)> trunc(22222222222222222222300.0)
22222222222222222688256
iex(7)> trunc(222222222222222222222300.0)
222222222222222218493952
Current the Kernel.trunc/1 just simply call :erlang.trunc/1:
@spec trunc(number) :: integer
def trunc(number) do
:erlang.trunc(number)
end
https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/kernel.ex#L730
Should we implement the trunc function on our own?
:erlang.round/1, :erlang.float_to_list/1 and :erlang.float_to_binary/1 also have the same bug:
iex(1)> :erlang.round(22222222222222222300.0)
22222222222222221312
iex(2)> :erlang.float_to_list(22222222222222222300.0)
'2.22222222222222213120e+19'
iex(3)> :erlang.float_to_binary(22222222222222222300.0)
"2.22222222222222213120e+19"
Floats have limited precision. Your number is too big, reaching out of float precision. If you need big numbers like that, consider using a library like decimal.
José Valim www.plataformatec.com.br Skype: jv.ptec Founder and Lead Developer
You are right. Thanks!