9 comments
One way to do this is to separate the computation/storage and presentation layer: use integers to store values as cents for computation/storage and only convert to dollars+cents on display. But then someone might suddenly demand three digits after the decimal point and you cannot go about changing every stored value just because the logic changed in one part of the application. So, using decimals is the safer choice.
I prefer integers for my plain text ledger software though because the format is in my control.
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).
amount_due = 0.10 + 0.20
amount_paid = 0.30
if amount_paid >= amount_due:
print("PAID")
else:
print("OUTSTANDING")
will print “OUTSTANDING”.They use binary fixed-point numbers/integers, where such computations are exact, while not having the huge computational overhead of decimal floating-point numbers.
The article's images clearly show the rounding error mess your get without decimals.
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.
Read the full thread on Hacker News →
Related stories
- Adding Floating-Point Decimals for Fun and Profitblog.vero.siteLobsters · 8 points · 2 days ago
- Hacker News · 1 points · 9 days ago
- More floating point alternativeswizardzines.comHacker News · 33 points · 12 days ago
- How do you compute the midpoint of an interval with floating point?hal.archives-ouvertes.frLobsters · 2 points · over 7 years ago
- Plotting floating-point aliasinghdevalence.caLobsters · 1 points · almost 12 years ago
- Myths About Floating-Point Numbers (2021)asawicki.infoLobsters · 12 points · about 1 year ago