Do your calculations in cents, or thousandths of cents or whatever precision is needed.
Don't get me wrong but it seems to be an anti-pattern and really hard to maintain. Not only in monetary calculations suffer same problem, that subtle rounding difference can create a whole mess in scientific applications too.
| [reply] |
Sure, but floating point calculations are not the solution. Either do a calculation of the error introduced by your calculations and the inexactness of floating point calculations, or avoid floating point calculations. Also read the article I linked. If you need a reproducible and exact calculations, use fixed point calculations.
| [reply] |
it seems to be an anti-pattern
No. It is not an anti-pattern here at all.
In fact is is the ONLY sensible thing to do.
That floats are not suitable to reprensent monetary amounts (ultimately because 0.1 is not a finite decimal in binary) is in fact so well known and has been so many times advised against that I am in fact surprised that anybody would consider this even for a second.
| [reply] |
Getting back to the Money example,
Let say you have a multi-currency app (my case), so you have to deal with a wide range of exchange ratios ( i.e ARS exchange ratio is 0.252 ), now lets assume your money engine is written using cents and the price for one item is 1.10 ARS ( 110 ARS cents ) and you convert it to USD ( 25.452 USD cents ), if we just ignore the floating part of the amount your number becomes 0.25 USD ( 25 USD cents), when you convert it back to the orginal currency you get 0.99 ARS ( ~10% error )
This situation is even worse than dealing floating point's error. And the more you need to do with the data the messier it becomes
| [reply] |
With respect, but if your floating point code creates "a whole mess" in scientific applications you are not writing good quality code.
Numerical analysts have recognized the issues which arise from rounding errors, truncation errors and quantization errors for a very long time now, certainly since before the invention of electronics. For around 200 years, since the days of Gauss at least, techniques and algorithms have been developed to help minimize inaccuracy in chains of computations on finite representations of real numbers.
Anyone who wishes to find out more on the subject should consult texts on numerical analysis. There are many good ones available.
Paul
| [reply] |