Sub topic 4
Representing money correctly
What this chapter assumes
You should be comfortable reading short Python and SQL snippets. You should know what a relational database column type is, and what an HTTP JSON payload looks like. Nothing else is needed. The chapter covers how a payment system stores, moves, and calculates money so that no cent is created or lost.
Why floating point fails
Most languages store float values in binary. Many decimal fractions, such as 0.1, have no exact binary form. Each one is stored as a close approximation, and the errors surface in arithmetic.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(sum([0.10] * 10) == 1.0) # False, the sum is 0.9999999999999999In a payment system, an error of a fraction of a cent breaks equality checks. It also makes ledger totals drift and causes reconciliation mismatches that are hard to trace. The fix is to never use binary floating point for money, in code, in the database, or in the API.
Integer minor units
The standard approach is to store an amount as an integer count of the currency's smallest unit, called the minor unit. For US dollars the minor unit is the cent, so $19.99 is stored as 1999. Integer addition and subtraction are exact, and every database and language supports them.
An integer alone is not enough, because 1999 means different things in different currencies. Always store the amount together with a currency code. Use the three-letter codes from ISO 4217, the international standard for currency codes.
Currencies have different exponents
The exponent is the number of decimal places between the major unit and the minor unit. It is not always 2.
| Currency | Exponent | Display amount | Stored minor units |
|---|---|---|---|
| USD | 2 | 19.99 | 1999 |
| JPY | 0 | 1999 | 1999 |
| KWD | 3 | 1.999 | 1999 |
The same stored integer can be about twenty dollars, about two thousand yen, or about two dinars. A hardcoded "divide by 100" is therefore a bug. Look up the exponent per currency, and load it from a maintained ISO 4217 table in production instead of typing it by hand.
Parsing amounts safely
Amounts usually arrive from outside as text or numbers. Convert them once, at the boundary, using exact decimal arithmetic. Reject anything that does not fit the currency instead of rounding it silently.
from decimal import Decimal, InvalidOperation
EXPONENTS = {"USD": 2, "EUR": 2, "JPY": 0, "KWD": 3}
def to_minor_units(amount: str, currency: str) -> int:
"""Convert a decimal string such as '19.99' to integer minor units."""
if currency not in EXPONENTS:
raise ValueError(f"unsupported currency {currency}")
try:
value = Decimal(amount).scaleb(EXPONENTS[currency])
except InvalidOperation:
raise ValueError(f"not a number: {amount!r}")
if not value.is_finite() or value != value.to_integral_value():
raise ValueError("amount has more precision than the currency allows")
return int(value)
print(to_minor_units("19.99", "USD")) # 1999
print(to_minor_units("1999", "JPY")) # 1999
print(to_minor_units("1.999", "KWD")) # 1999to_minor_units("10.005", "USD") raises an error. That is correct. Half a cent cannot be charged, and silently picking a direction would hide a client bug.
Always pass the amount as a string to Decimal. Decimal(0.1) would copy the float's error into the decimal value.
Money as a value object
Pairing the integer with its currency in one immutable object stops you from mixing currencies by accident.
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
minor: int
currency: str
def __add__(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError(f"cannot add {self.currency} and {other.currency}")
return Money(self.minor + other.minor, self.currency)
print(Money(1999, "USD") + Money(1, "USD")) # Money(minor=2000, currency='USD')Adding USD to EUR has no meaningful answer without an exchange rate, so the class refuses to guess. Converting between currencies is a separate, explicit operation, described below.
Storing money in the database
Use BIGINT for the amount and a fixed-width currency column, as in the payments table from the idempotency chapter. A CHECK constraint adds a last line of defense against bad data.
CREATE TABLE fx_conversions (
id UUID PRIMARY KEY,
source_amount_minor BIGINT NOT NULL CHECK (source_amount_minor > 0),
source_currency CHAR(3) NOT NULL CHECK (source_currency ~ '^[A-Z]{3}$'),
target_amount_minor BIGINT NOT NULL CHECK (target_amount_minor > 0),
target_currency CHAR(3) NOT NULL CHECK (target_currency ~ '^[A-Z]{3}$'),
rate NUMERIC(20,10) NOT NULL CHECK (rate > 0),
quoted_at TIMESTAMPTZ NOT NULL
);A 64-bit integer holds about 9.2 × 10^18 minor units. That is far beyond any single payment, and enough for most aggregates. Avoid the MONEY type in some databases, because its precision and formatting can depend on locale settings. NUMERIC is exact too, but integers are simpler and faster, and they map cleanly to every language.
For exchange rates, NUMERIC is appropriate, because a rate is a ratio and not an amount of money.
Money in the API
Two representations are common in JSON:
- An integer in minor units plus a currency code, such as
{"amount": 1999, "currency": "USD"}. - A decimal string plus a currency code, such as
{"amount": "19.99", "currency": "USD"}.
Both are safe. Avoid a bare JSON number like 19.99, because many JSON parsers read it as a binary float. Document which representation you use, and always include the currency. Whichever you choose, use it for every endpoint, webhook, and report.
JavaScript clients also lose integer precision above 2^53 − 1 (9,007,199,254,740,991). That is enough for any single payment, but sums of many payments can pass it. Send large totals as strings.
Rounding and splitting
Rounding is unavoidable when you calculate a percentage, such as a processing fee. The rule is to round once, at a defined step, using a documented mode, and to store the rounded integer.
from decimal import Decimal, ROUND_HALF_EVEN
def percentage_fee(amount_minor: int, rate: str) -> int:
fee = Decimal(amount_minor) * Decimal(rate)
return int(fee.quantize(Decimal("1"), rounding=ROUND_HALF_EVEN))
print(percentage_fee(1999, "0.029")) # 58, from 57.971ROUND_HALF_EVEN, also called banker's rounding, rounds exact halves to the nearest even number. This avoids a systematic upward bias across millions of payments. Your contract with a merchant may specify another mode, so follow the contract.
Splitting an amount is a related problem. Dividing 100 cents three ways gives 33.33 cents each, and the pieces must still add up to exactly 100. Allocate the remainder one unit at a time.
def allocate(total: int, weights: list[int]) -> list[int]:
"""Split a non-negative total in proportion to positive weights."""
weight_sum = sum(weights)
shares = [total * w // weight_sum for w in weights]
remainder = total - sum(shares)
for i in range(remainder):
shares[i] += 1
return shares
print(allocate(100, [1, 1, 1])) # [34, 33, 33]
print(sum(allocate(100, [1, 1, 1]))) # 100The shares always sum to the original total, so a ledger built from them stays balanced.
Currency conversion
When a payment crosses currencies, store everything that produced the result: the source amount and currency, the target amount and currency, the rate, and the quote time, as in the fx_conversions table. Never recompute an old conversion from today's rate. The stored values are the record.
How the pieces fit
Conversion to and from decimals happens only at the edges: parsing input and formatting output. The core of the system never sees a float.
Common errors
- Using
floatordoubleanywhere on the money path. This includes intermediate values in fee calculations. - Assuming two decimal places. JPY and KWD break that rule.
- Storing an amount without a currency. The number is meaningless on its own.
- Rounding silently. Reject or log amounts with excess precision, and round only where a rule says to.
- Rounding each piece independently when splitting. The pieces then may not add up to the total.
- Converting at read time. Persist the conversion result and its rate.
Exercise
A client sends {"amount": "5.5", "currency": "JPY"}. What should to_minor_units do, and why?
Show answer
It should raise an error. JPY has exponent 0, so the minor unit is the whole yen. The scaled value 5.5 is not an integer, which means the amount has more precision than the currency allows. Rounding it to 5 or 6 would hide a client bug and change the amount charged.
Exercise
A fee of 1000 minor units must be split among three sellers with weights 1, 1, and 1 using allocate. What are the shares, and why must they sum to exactly 1000?
Show answer
The shares are [334, 333, 333]. Each seller first gets 1000 * 1 // 3 = 333, which leaves a remainder of 1, and that unit goes to the first seller. The shares must sum to exactly 1000 because the ledger requires debits to equal credits. A total that is off by even one minor unit would make the transaction unbalanced.