Sub topic 4
Representing money correctly
This chapter assumes you know basic Python and SQL, and that you know why floating-point numbers are imprecise. It covers how a payment system should store and move amounts.
Why floats fail
Binary floating point cannot represent most decimal fractions exactly. In Python, 0.1 + 0.2 gives 0.30000000000000004. A single error like that is tiny, but a payment system adds and splits amounts millions of times. The errors accumulate, and the ledger stops balancing by a cent that nobody can explain.
Use integer minor units
Store every amount as an integer count of the currency's smallest unit, called the minor unit. In US dollars, $19.99 is stored as 1999 cents. Integer arithmetic is exact, so sums and comparisons are reliable.
Not every currency has two decimal places. The ISO 4217 standard defines the exponent for each currency:
| Currency | Minor unit | Exponent | 10.00 stored as |
|---|---|---|---|
| USD | cent | 2 | 1000 |
| JPY | yen (none smaller) | 0 | 10 |
| KWD | fils | 3 | 10000 |
Never assume the exponent is 2. Look it up per currency.
Always pair an amount with a currency
A bare number is ambiguous, because 1000 could be $10.00 or ¥1000. Store the currency code next to every amount, and refuse to add or compare amounts in different currencies. The payments table in the idempotency chapter already does this with amount_minor BIGINT and currency CHAR(3). Use BIGINT, not a 32-bit integer, because large totals overflow 32 bits quickly.
Convert at the edges only
Clients often send amounts as decimal strings. Convert them once at the API boundary, using Decimal and never float. Reject input that has more precision than the currency allows, instead of silently rounding it.
from decimal import Decimal
from collections import defaultdict
def to_minor_units(amount: str, exponent: int = 2) -> int:
"""Convert a decimal string such as '19.99' to integer minor units (1999)."""
value = Decimal(amount).scaleb(exponent)
if value != value.to_integral_value():
raise ValueError("amount has more precision than the currency allows")
return int(value)
def assert_balanced(entries):
"""entries: iterable of (account, direction, amount_minor, currency)."""
net = defaultdict(int)
for _account, direction, amount, currency in entries:
net[currency] += amount if direction == "debit" else -amount
if any(total != 0 for total in net.values()):
raise ValueError("ledger transaction is not balanced")
assert_balanced([
("customer_funds_receivable", "debit", to_minor_units("19.99"), "USD"),
("merchant_payable", "credit", to_minor_units("19.99"), "USD"),
])assert_balanced checks that debits equal credits separately for each currency. The ledger chapter builds on this check.
Common errors
- Passing floats through JSON. Many JSON parsers read
19.99as a float. Send amounts as integer minor units or as strings. - Rounding when splitting. Splitting 100 cents three ways gives 33, 33 and 33, so one cent is lost. Distribute the remainder explicitly, for example by giving the extra cent to the first share.
- Converting currencies without recording the rate. If you convert, store the rate, its timestamp, and both amounts. Otherwise you cannot reproduce the result later.
Exercise
A client sends the amount "5.5" for a JPY payment (exponent 0). What should to_minor_units("5.5", 0) do, and why?
Show answer
It should raise a ValueError. Yen has no minor unit smaller than 1, so 5.5 has more precision than the currency allows. Rounding silently would change the amount the customer agreed to pay.