elixirmoney / money

Elixir library for working with Money safer, easier, and fun... Is an interpretation of the Fowler's Money pattern in fun.prog.
https://hex.pm/packages/money/
MIT License
826 stars 139 forks source link

fix: avoid float rounding in Money.to_string #139

Closed polvalente closed 4 years ago

polvalente commented 4 years ago

Big numbers like 123_456_789_123_456_789_123_456_789_123_456_789 suffer from float rounding errors due to the way the conversion in Money.to_string is implemented.

This PR aims to avoid such problems by performing the initial conversion and split using Integer and String functions only.

The following example (included in the new assertions I added) shows the bug.

iex(1)> 123_456_789_123_456_789_123_456_789_123_456_789 |> Money.new(:USD) |> Money.to_string
"$1,234,567,891,234,567,846,791,203,981,885,440.00"
iex(2)> Money.new(123_456_789_123_456_789_123_456_789_123_456_789, :USD) |> Money.to_string == "$1,234,567,891,234,567,891,234,567,891,234,567.89"
false
Nitrino commented 4 years ago

@polvalente Great work. Thanks! 🔥