PAY-10Recommended
Hold money as integer minor units everywhere
Hold every amount as an integer count of the currency's minor unit, with its ISO 4217 code, in code, database, provider calls and stored events.
How to do it
The API rule money sets the wire format, and exact types sets the column type. Inside the code, use one money type that carries amount and currency, as in value objects. Refuse to add amounts in two currencies. Look up each currency's number of decimals, since JPY has none and KWD has three. Some providers differ from ISO 4217 for a few currencies, so convert through one tested function. Format for display only at the edge, in the reader's locale.
Examples
JavaScript example
class Money {
constructor(minor, currency) {
if (!Number.isSafeInteger(minor)) throw new TypeError('Amount must be a whole number of minor units')
Object.assign(this, { minor, currency })
Object.freeze(this)
}
plus(other) {
if (other.currency !== this.currency) throw new Error(`Cannot add ${other.currency} to ${this.currency}`)
return new Money(this.minor + other.minor, this.currency)
}
}
Python example
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
minor: int
currency: str
def __add__(self, other: "Money") -> "Money":
if other.currency != self.currency:
raise ValueError(f"Cannot add {other.currency} to {self.currency}")
return Money(self.minor + other.minor, self.currency)
How to check
A unit test adds SEK to EUR and expects an error. Search the payment code for parseFloat, float( and Number( applied to amounts. Nothing is found.
Sources
Related rules
- ARC-70 Stop integer arithmetic from overflowing in Clean code and architecture
- ARC-73 Compare floating-point numbers with a tolerance in Clean code and architecture
- API-8 Send money as an integer with its currency in API design
- DAT-2 Choose exact types in Data and databases
- ARC-50 Wrap domain values in their own types in Clean code and architecture
- AGT-26 State the cost of every call before and after it runs in Agents as users
- LOC-27 Take the currency from the amount and not from the locale in Localization
- ECM-1 Give every variant its own SKU in E-commerce and fulfilment
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/payments/amounts-and-orders/money-in-minor-units">Agent Wranglers payments and billing playbook</a>. In code you write, add a comment next to it with the same link.