Storing money amounts correctly in programs
In short: Money is never stored as a floating-point number (float/double), but as an integer in the smallest unit (cents) or as an exact decimal type.
In more detail: Binary floating-point numbers cannot represent many decimal fractions exactly. 0.1 + 0.2 gives 0.30000000000000004 in most languages. With amounts such deviations add up.
In Depth
- Whole cents: €19.99 is stored as
1999. Addition and comparison are exact. Divide by 100 only for display. - Decimal types:
DECIMAL(12,2)in SQL,BigDecimal(Java),Decimal(Python, C#). They calculate in base ten. - Carry the currency: Amount and currency code (EUR, JPY …) belong together. Not all currencies have two decimal places (JPY: 0, KWD: 3).
- Rounding: The rounding rule must be set by the business (commercial, banker’s rounding) and applied only at the end of calculation chains. Percentages and taxes produce fractions of a cent.
- Splitting: When dividing (€100 among 3) a remainder cent is left that must be assigned deliberately.
- Exchange: In JSON transfer amounts as a string or whole cents, not as a number with decimals.
See also: floating-point number