The float trap
Storing money as a floating point number invites rounding errors because values like ten cents cannot be represented exactly in binary. Over many operations these tiny errors accumulate into real discrepancies.
The safe representation
Store an amount as an integer count of the minor unit for its currency, paired with a currency code. Ten dollars becomes the integer one thousand cents plus the code USD.
- Different currencies have different numbers of decimal places, so the code is required to interpret the integer.
- Never compare or add amounts of different currencies without an explicit conversion.
Conversion and rounding
- When converting currencies, apply the exchange rate and choose a rounding rule, then record both the rate and the rounded result.
- Keep rounding deterministic so two systems computing the same value agree.
Key idea
Represent money as integer minor units bound to an explicit currency, never as a float, so arithmetic stays exact and currencies never silently mix.