> Many people know that you shouldn’t do decimal calculations, such as those involving U.S. dollars and cents, with the floating-point numbers in most programming languages. This is because decimal numbers can’t be expressed exactly as such floating-point numbers, so you will encounter rounding errors.
Why not, rounding to the nearest cent is going to be much less precise for any realistic amount of dollars when using 64 bit floats (the type of float Javascript uses in every browser).
I think there’s an implicit assumption with this sort of “use a special decimal type” advice: that the rules of the transactions are defined in terms of decimal rounding.
I mean, just as an example, your savings account interest could be computed continuously, e^(rt), which would obviously be better approximated in floating point than some decimal type. But they won’t have to do any approximation if they write the contract so that the value compounds nightly and is rounded to the nearest, whatever, tenth of a cent (which means that the rounding isn’t an approximation at all, it is part of the definition of the value being represented).
The rounding behavior with true decimals is easy to control and understand across number magnitudes and doesn't suffer from platform specific quirks like floats/doubles.
The article's images clearly show the rounding error mess your get without decimals.
"The nearest cent" is already a bad assumption. Should IEEE 754 representation dictate taxes and money splitting?
You could end up with splitting an account down the middle, and ending up with an extra cent being created out of thin air, or one destroyed. In billions of transactions each day, this could be a problem for balancing books when there is no longer any equality check.
When not using floats, the rules and checks become more… deterministic, if you don't mind stretching the definition of that word a bit.
It’s easier just to use a proper decimal type than to remember all of the ways where using floats will bite you in the ass. The behavior is unintuitive even in trivial examples. Code like
will print “OUTSTANDING”.