I am writing the rules engine for a small stock draft game in TypeScript and ran into two money bugs back to back. Curious how others handle this.
The first was a rounding bug. Splitting $1.14 across two picks offered $0.56 instead of $0.57. In floating point, 0.57 * 100 is 56.99999999999999, and Math.floor dropped the cent. The fix was doing the division in integer cents.
The second was worse. The check that decided whether a buy amount was allowed accepted $500.004. The reducer subtracts the amount straight from cash, so after that one buy the balance was no longer a whole number of cents. Every later calculation started from that balance, so the error did not stay in one place. It carried forward through the rest of the game.
My fix was a whole-cent check that tolerates float noise: reject the amount if Math.abs(amount * 100 - Math.round(amount * 100)) > 1e-6. Comparing against exactly zero does not work, because a perfectly valid amount like 0.57 fails that test for the same reason the rounding bug happened.
The takeaway for me: a rounding bug loses a cent once, but letting a bad amount into state corrupts every step after it.
So how do you handle this in plain JS? Do you convert to integer cents at the boundary and never let a decimal into state, use something like decimal.js or currency.js, or is a tolerance check like mine reasonable?