#Int vs Decimal
28 messages · Page 1 of 1 (latest)
Decimal has an advantage in form that it do not limit you to single monetary unit (not all currencies divide into 100s)
never use floats for money, that’s the only solid advice. there are some elixir packages that handle money like https://hexdocs.pm/money/Money.html
Also, in some monetary computations you need fractions of minimal monetary unit
nice
I didn't know about this lib. I will look
thing is, Decimal requires a certain standardization in the projects. These days I did the following: #Decimal<0.5> == #Decimal<0.5000> and got a false as a result
with int numbers we don't have this problem since all right 0s are ignored after the comma
but I found out Decimal.equal?
rs
Floating point comparisons will fail in that way for nearly every language. https://0.30000000000000004.com/
Yeah, that’s why in my initial comment I said to avoid using floats (decimals are a float) for money
btw, a very famous digital bank here in Brazil had problems with this recently
it was impossible to transfer 17.99R$
the system rounded the value to 17.98 every time
😂
No, Decimal library is not float
i’ve never used this specific package, but given that decimal in every context to me means a float, this strikes me as weird. can’t reason why #Decimal<0.5> == #Decimal<0.5000> being false then
No, decimal in any context mean decimal, floats in general mean IEEE 754 binary32/binary64 format. And the reason why #Decimal<0.5> == #Decimal<0.5000> is not equal is the same why %Foo{a: 1, b: 2} != %Foo{a: 2, b: 4}, their internal representation is different and that is why you cannot use == there and you must use Decimal.equal?/2
floating point is only one way of handling decimal numbers
If anything, decimals can mean IEEE 754 decimal format, which is similar to what Decimal uses internally, but decimals are perfectly fine for money storage, as it avoid most of the issues related to the rounding coming from the binary encoding
The problem with IEEE 754 binary for money comes not from the fact that it is floating point, but from the fact that it has limited precision and that it uses base 2 for computations. If you have unlimited precision floating points in base 10, then there is no issue
TIL. looked into the Decimal package itself, it uses some pretty clever tricks to avoid ever dividing numbers and multiplies with multiplicands and their base10 exponents to compute new significant figures and exponents
Yes, because division is super costly in general sense. In x86-64 assembly it is faster to add hundreds of integers than to divide just two.
And that is even without SIMD magic
I prefer this library, it has excellent integration with cldr, knows all the details and nuance of all currencies, like rounding rules and stuff: https://hexdocs.pm/ex_money/Money.html