Money in software: minor units, rounding, currencies
A float cannot hold ₦0.10, a percentage has to land on a whole kobo, and a split has to add back to the total. Decide each rule once, write it down, and test it against real data
Owoleaf charges card fundings a fee of 1.5% of the amount, rounded to the nearest kobo. A customer funds ₦1,823.00 (182,300 kobo) by card. The lab's ledger has this funding. What is its fee in kobo?
A minor unit is the smallest unit of a currency that the system counts: the kobo for the naira, the pesewa for the cedi, the cent for the rand and the shilling. The major unit is the one people name prices in. The exponent is the number of decimal places between them: 2 for the naira, because 100 kobo make ₦1. A money amount in software is two things together: an integer count of minor units and a currency code. The rest of this chapter is about the three places where that pair gets damaged: when it is stored, when it is rounded, and when it is split or converted.
A float cannot hold ₦0.10
A computer stores a floating-point number in binary. A tenth has no exact binary form, in the way a third has no exact decimal form, so the machine keeps the nearest binary fraction it can. You can see what it actually keeps:
from decimal import Decimal
print(0.1 + 0.2)
print(Decimal(0.1))
print(8.29 * 100)
0.30000000000000004
0.1000000000000000055511151231257827021181583404541015625
828.9999999999999
The first line is the famous one. The third is the one that costs money: a price of ₦8.29, multiplied by 100 to get kobo and cut to a whole number with int(), becomes 828 kobo. One kobo disappears, with no error and no warning. Across the prices from ₦0.01 to ₦999.99, int(float(price) * 100) is one kobo short for 4,586 of 99,999 of them. You will count that in the break step of the lab.
Summing makes it worse, because each addition keeps the error from the last. Owoleaf’s ledger has 191,103 entries. As integers they sum to 394,277,129,928 kobo, which is ₦3,942,771,299.28. As float naira, added one at a time, they sum to 3942771299.279976. The float is short by about a four-hundredth of a kobo. That is far too small to see in one number and enough to make an equality check fail: total == 3942771299.28 is False.
From Python 3.12, the built-in sum() uses a compensated algorithm (Neumaier summation) when it adds floats, so it can return a more accurate float than the same loop on Python 3.11 or earlier; this rests on search summaries of the CPython change request, because the “What’s New” page could not be openedas of 2026-11. That makes the problem harder to see, not smaller. On the Python 3.13 used to write this chapter, sum() over the same entries returned 3942771299.28, while an explicit total += kobo / 100 loop returned 3942771299.279976. The lab uses the explicit loop, so the result is the same on every version. The same code on two machines giving two answers is itself the warning.
Three rules follow, and they are the whole of this section:
- Never store or add money as a float. Store integer kobo. Add integers; Python’s integers do not overflow or drift.
- Never compare money with
==on floats. If you must show a float, show it at the edge, for a human, and never use it again. - Parse text to integers directly. Do not go through a float on the way in. The lab’s
to_minorreads"8.29"as aDecimal, which is exact, and refuses to continue if the text has more decimals than the currency allows.
The lesson on money in floating point lets you watch the same failures in a simulation; this chapter takes them into a ledger.
Integers of minor units, and the currency beside them
Once money is an integer of minor units, one question remains: how many decimals does a minor unit imply? The exponent comes from a standard. ISO 4217, from the International Organization for Standardization (ISO), is the international standard for currency codes, with a “minor unit” (exponent) for each currency, and its amendments are handled by a maintenance agency, SIX Financial Information on behalf of the Swiss member of ISOas of 2026-11. The exponents used here are 2 for NGN (naira), GHS (cedi), KES (Kenyan shilling), ZAR (rand) and USD (US dollar), 0 for JPY (yen) and 3 for KWD (Kuwaiti dinar). This chapter could read those exponents only from secondary listings that quote the standard (the ISO page it cites confirms the agency arrangement, not the table), so check the current list on the agency’s own site before you copy a table into production code.
The trap is that Wrenpost’s four currencies all have exponent 2. Code with * 100 and / 100 hard-coded passes every test written in naira, cedis, shillings and rand. It breaks the day a yen or a Kuwaiti dinar arrives: ¥1,000 is the integer 1000, and dividing by 100 books ¥10.00. The lesson on minor units and currencies shows that failure in a simulation. In code, the fix is to keep the currency with the integer and look the exponent up in one table, in one place.
Payment providers add their own conventions on top of the standard. Stripe’s currency documentation (a vendor’s claim about its own API) lists zero-decimal currencies, whose amounts are sent as whole units, and notes that ISK (Icelandic króna) and UGX (Ugandan shilling) have to be sent as two-decimal values ending in 00 for backwards compatibilityas of 2026-11. The exact list changes, and this chapter confirmed the page only through search summaries, so read the current page. The lesson is the general one: the table belongs to each API you talk to, not to the world. When Owoleaf’s payment provider sends an amount, the integer’s meaning is in the provider’s documentation.
Two practical consequences. First, reject, do not round, input that has too many decimals. A customer typing ₦12.345 has made an error, not a request for a rounding rule; to_minor("12.345", "NGN") raises an error. Second, an amount without a currency is not money. A column called amount_kobo is safe because the unit is in its name. A column called amount in a table that will one day hold cedis is a bug that has not yet happened.
Do the kobo exist at all outside software? The Central Bank of Nigeria’s legal tender page exists and shows images of banknotes and coins, but a search summary of it gave no text list of the denominations; it mentioned images of a 1 kobo coin, a 10 kobo coin, a ₦1 coin and the ₦200, ₦500 and ₦1,000 notesas of 2026-11. Secondary sources list eight banknotes, ₦5 to ₦1,000, and only 50 kobo, ₦1 and ₦2 as current coins, and say coins from half a kobo to 25 kobo were withdrawn on 28 February 2007. The sources are incomplete and partly disagree, and this chapter could not open the CBN page itself. The point for a payments engineer survives either way. The kobo is a unit of account that a ledger and a transfer message carry to the last digit, whether or not anyone can hold a 1-kobo coin. Card fees, interest and foreign-exchange (FX) conversions routinely produce fractions of a kobo, and the system must decide what to do with them.
Rounding is a rule, and the rule is part of the contract
Take Owoleaf’s card funding fee: 1.5% of the amount, capped at ₦2,000, in the generator’s illustrative price list. The fee is almost never a whole number of kobo. A ₦1,823.00 funding is 182,300 kobo, and 182,300 × 0.015 = 2,734.5. Somebody must pick 2,734 or 2,735.
Four rules cover nearly every case:
| Rule | 2,734.5 | 2,735.5 | 2,733.4 | What it does |
|---|---|---|---|---|
| Round half up (ties go up) | 2,735 | 2,736 | 2,733 | Always favours the larger value on a tie. |
| Round half even (ties go to the even neighbour) | 2,734 | 2,736 | 2,733 | Ties go up half the time and down half the time. |
| Round down (cut) | 2,734 | 2,735 | 2,733 | Always favours the smaller value. |
| Round up (ceiling) | 2,735 | 2,736 | 2,734 | Always favours the larger value, even off a tie. |
Round half up is what most people learn. Round half even is also called banker’s rounding. The difference matters because of what a tie costs. Half up pushes every tie the same way, so across many transactions it adds a small bias. Half even splits ties both ways and the bias cancels. Python’s decimal module uses half even as the default rounding of its context (ROUND_HALF_EVEN), and offers ROUND_HALF_UP and other modes by nameas of 2026-11. The module follows Mike Cowlishaw’s General Decimal Arithmetic specification (see Reading), which defines each rounding mode. Python’s built-in round() is half even as well: round(2.5) is 2 and round(3.5) is 4.
Now the data. The generator rounds the fee with Python’s round, so it is half even, and the lab recomputes every fee with exact Decimal arithmetic and each rule. Of the 10,280 card fundings that succeeded:
- Half even disagrees with
fee_koboon 0. - Half up disagrees on 2,586, and every difference is exactly +1 kobo.
- Added up, half up would charge customers ₦25.86 more than the ledger holds over 180 days at scale 0.1.
Why 2,586, and why is the figure around a quarter of all fundings? Every funding amount in the data is a whole number of naira, and 1.5% of a whole naira is 1.5 kobo per naira. So the fee has a half kobo exactly when the naira amount is odd, and the lab counts 5,152 such exact ties. On a tie, half even rounds to the even kobo. Half up rounds up. They agree when the lower neighbour is odd and differ when it is even, which happens in 2,586 of the 5,152 ties. Tie counts depend on the price list: at 1.4% there would be none, because 1.4% of a whole naira is 1.4 kobo, and 14 × n is even while a half kobo needs an odd tenth. The lesson is the mechanism, not the number.
The generator itself uses a float, round(amount * 0.015), and it agrees with the exact result on every row; the lab shows this in step 3. A wider check, over every amount from 1 kobo to 19,999,999 kobo (up to ₦199,999.99), found no disagreement either. That is luck, not design: the float 0.015 is really 0.01499999999999999944488848768742172978818416595458984375, slightly below 0.015, and the multiplication happens to round back onto the half in those cases. Do not rely on it. The lab’s card_fee uses Decimal("0.015"), built from a string, so the rate is exact.
Who chooses the rule
Nobody in your company chooses it alone. When Owoleaf computes a fee and a partner bank or a provider computes the same fee, the two must produce the same kobo or the reconciliation shows a break. The rule is therefore part of the contract with the other side: the provider’s documentation, the bank’s statement format, the regulator’s circular if there is one. Where nobody else has decided, you write the rule down: the rate as an exact decimal, the rounding mode by name, the step at which rounding happens, and the cap. The double-entry chapter later in this module shows why two sides must agree on every figure, and the reconciliation chapter in module 2 shows what happens when they do not.
Round once, at the end. If you round a rate to two decimals, then round the product, then round a tax on it, each step adds its own error and the total no longer matches a system that rounds once. The conversion example below shows it.
Caps and thresholds
The card fee has a cap: it is the smaller of 1.5% of the amount and ₦2,000. A cap hides a threshold, and the threshold is worth knowing before a customer finds it.
The exact working: the fee reaches the cap when 0.015 × amount = 200,000 kobo, so amount = 200,000 ÷ 0.015 = 13,333,333.33 kobo, or ₦133,333.33. Above that amount the percentage would exceed ₦2,000 and the cap holds the fee at 200,000 kobo. The effective rate then falls: at the largest funding in the data, ₦592,110.00, ₦2,000 is 0.3378% of the amount.
Rounding moves the edge slightly. At 13,333,300 kobo (₦133,333.00) the exact fee is 199,999.5, a tie, and half even rounds it to 200,000, which equals the cap. The unrounded fee first rounds to a figure above the cap at 13,333,367 kobo, because 13,333,367 × 0.015 = 200,000.505. So three nearby figures describe the same cap: ₦133,333.00 where the fee first equals 200,000 kobo, ₦133,333.33 where the exact percentage passes it, and 13,333,367 kobo (₦133,333.67) where rounding alone would give more than the cap. A boundary test needs all three.
In the data, 31 successful card fundings are above the cap, from ₦135,935.00 to ₦592,110.00, and all 31 carry a fee of exactly 200,000 kobo. The cap gives up 3,119,190 kobo, ₦31,191.90, of fees that the percentage alone would have charged on those 31. Whether that is a good price is a question for the pricing chapter in module 3. This one only insists that the threshold be computed from the rule, and tested at its edges.
Splitting an amount without losing a kobo
A fee has to be shared, a bill has to be split, a settlement has to be allocated across merchants. Divide ₦100.00 (10,000 kobo) by three and every share is 3,333.33 kobo. Round each to the kobo and you have 3,333 × 3 = 9,999 kobo: a kobo that exists in the total and belongs to nobody. It does not matter which rounding mode you pick, because there is no tie to break; the shares do not add up.
The fix is to allocate, not to round. Largest-remainder allocation has three steps:
- Floor each share: total × weight ÷ sum of weights, cut to a whole kobo.
- Count the leftover kobo: the total minus the sum of the floored shares.
- Give one leftover kobo to each of the shares with the largest fractional remainder, until none is left. Break ties by a fixed order that you write down.
For ₦100.00 in three equal parts, the floors are 3,333, 3,333 and 3,333, one kobo is left, all three remainders tie, and the first share takes it: 3,334, 3,333, 3,333. The shares always sum to the total, and the extra kobo goes somewhere you can name. Fowler’s Money pattern in Patterns of Enterprise Application Architecture describes an allocate operation for the same job; search summaries of ports of it say leftover units go to the first shares in order, and this chapter could not open the book’s code to confirm that. The largest-remainder version is a refinement that treats unequal weights more fairly. The lesson on the residual cent lets you watch the difference.
The tie-break is part of the rule. Allocating 5 kobo by weights 70 and 30 gives 4 and 1; by weights 30 and 70 it gives 2 and 3. Both remainders tie at one half, and the earlier share wins, so the order in which you list the shares changes who gets the kobo. Fix that order by something stable, such as customer id, never by arrival time.
Converting between currencies
Wrenpost’s invoice shows the same problem with a rate in the middle. Three lines of GH₵19.99 are 1,999 pesewas each. In the lab’s illustrative rate of 97.25 naira to the cedi, which is not a market rate, each line is 19.99 × 97.25 = ₦1,944.0275, which is 194,402.75 kobo and rounds to 194,403. Three lines make 583,209 kobo. The whole invoice, GH₵59.97 × 97.25 = ₦5,832.0825, is 583,208.25 kobo, which rounds to 583,208. The two ways of adding differ by one kobo, which is Ogechi’s one kobo from the opening.
Neither is a bug in arithmetic. The rule is missing. The usual rule has three parts:
- Convert and round the total once. The invoice total is the figure the customer pays, so it is the figure that is converted.
- Allocate that converted total to the lines in proportion to their original amounts, so the lines add up to it. Here the allocation is 194,403, 194,403 and 194,402.
- Store the rate and its source with the invoice. A rate is a ratio, not money, so it can be a
Decimal, but it is an input, and a conversion nobody can repeat is a conversion nobody can audit.
The exponent changes in conversion too. In the lab, 1,000 JPY (the integer 1000, exponent 0) at an illustrative 10.1 naira to the yen is ₦10,100.00, which is the integer 1,010,000 in kobo. The conversion function reads the source exponent, scales to major units, multiplies by the rate, scales to the destination exponent and rounds once. Cross-border chapters in module 3 take rates, spreads and costs further; the rule here is only that the rounding step is single and named.
Where it goes wrong
A float on the way in. int(float("8.29") * 100) is 828. Parse text with Decimal, or split on the point, and keep the result as an integer.
A float in the middle. Even if the input and the storage are integers, a * 0.015 in one function and a Decimal("0.015") in another will agree until the day they do not. One function, one rate, one type.
A hard-coded 100. Right for the naira, the cedi, the shilling and the rand, and wrong for the yen and the dinar. Look the exponent up, and keep a yen and a dinar in the test fixtures.
Two systems, two rounding rules. A provider that rounds half up and a ledger that rounds half even disagree on about a quarter of the lab’s card fundings, by one kobo each. The sum of those differences is small and the number of lines to explain is large.
Rounding at every step. Round once, at the end, after the full calculation. State the step.
Rounding a split. Share out remainders with a written rule instead; do not round each share.
A threshold computed by eye. A cap, a tier boundary or a limit is exact arithmetic on the rule. Test at the edge, one kobo each side.
You work in labs/finance, on Owoleaf’s generated books (seed 42, scale 0.1). The fee rate, the ₦2,000 cap and the conversion rates are illustrative, set in the generator and in your own code; none is a regulator’s or a bank’s. Money stays in integer kobo.
1. Add the ledger up two ways. If data/finance.sqlite is not there yet, run python3 generate.py && python3 check.py first. Then add every entry as integer kobo, and again as float naira in an explicit loop.
cd labs/finance
python3 - <<'EOF'
import sqlite3
db = sqlite3.connect("data/finance.sqlite")
total_float = 0.0
for (kobo,) in db.execute("SELECT amount_kobo FROM entries ORDER BY id"):
total_float += kobo / 100
total_int = db.execute("SELECT SUM(amount_kobo) FROM entries").fetchone()[0]
print("integer kobo:", total_int)
print("exact naira: ", f"{total_int // 100}.{total_int % 100:02d}")
print("float naira: ", repr(total_float))
print("float == exact?", total_float == total_int / 100, "| times 100:", total_float * 100)
print("0.1 + 0.2 =", 0.1 + 0.2)
EOFinteger kobo: 394277129928
exact naira: 3942771299.28
float naira: 3942771299.279976
float == exact? False | times 100: 394277129927.99756
0.1 + 0.2 = 0.30000000000000004The integer total is exact. The float is short by about 0.0024 kobo and fails the equality check, although each entry on its own is a harmless-looking division by 100. The loop is explicit on purpose: from Python 3.12 the built-in sum() compensates, and would hide the drift on a newer interpreter.
2. Write the money module. Save this as money.py in labs/finance. It holds the exponent table, a parser that refuses extra decimals, the fee rule, the allocator and the converter. Later steps import it.
cat > money.py <<'EOF'
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
# ISO 4217 exponents: digits after the decimal point in the currency's minor unit.
EXPONENT = {"NGN": 2, "GHS": 2, "KES": 2, "ZAR": 2, "USD": 2, "JPY": 0, "KWD": 3}
def to_minor(text, currency):
"""'8.29' and 'NGN' -> 829. Refuses more decimals than the currency has; never rounds."""
exp = EXPONENT[currency]
d = Decimal(text) * (10 ** exp)
if d != d.to_integral_value():
raise ValueError(f"{text} has more than {exp} decimals for {currency}")
return int(d)
def show(minor, currency):
exp = EXPONENT[currency]
return f"{Decimal(minor).scaleb(-exp):,.{exp}f} {currency}"
def card_fee(amount_kobo, rounding=ROUND_HALF_EVEN, rate="0.015", cap=200_000):
"""The generator's rule: 1.5% of the amount, rounded to the kobo, capped at 200,000 kobo."""
fee = (Decimal(amount_kobo) * Decimal(rate)).quantize(Decimal(1), rounding=rounding)
return min(cap, int(fee))
def allocate(total, weights):
"""Split an integer total by integer weights. Floor every share, then give the leftover
units one each to the largest fractional remainders (ties: the earlier share first)."""
s = sum(weights)
shares = [total * w // s for w in weights]
left = total - sum(shares)
order = sorted(range(len(weights)), key=lambda i: (-(total * weights[i] % s), i))
for i in order[:left]:
shares[i] += 1
return shares
def convert(minor, src, dst, rate):
"""rate = units of dst major per 1 src major, a Decimal. Round once, half to even."""
major = Decimal(minor).scaleb(-EXPONENT[src]) * rate
return int((major * 10 ** EXPONENT[dst]).quantize(Decimal(1), rounding=ROUND_HALF_EVEN))
EOF
python3 - <<'EOF'
from money import EXPONENT, to_minor, show
print(to_minor("1500.50", "NGN"), to_minor("1000", "JPY"), to_minor("12.345", "KWD"))
for text, cur in (("12.345", "NGN"), ("0.5", "JPY")):
try:
to_minor(text, cur)
except ValueError as e:
print("refused:", e)
print(show(150050, "NGN"), "|", show(1000, "JPY"), "|", show(12345, "KWD"))
EOF150050 1000 12345
refused: 12.345 has more than 2 decimals for NGN
refused: 0.5 has more than 0 decimals for JPY
1,500.50 NGN | 1,000 JPY | 12.345 KWD₦1,500.50 is 150,050 kobo, ¥1,000 is 1000 and KWD 12.345 is 12,345 fils. Text with too many decimals is refused instead of silently rounded.
3. Recompute every card fee with three rules. Take the 10,280 card fundings that succeeded and compare fee_kobo with half-even, half-up and the generator’s own float expression.
python3 - <<'EOF'
import sqlite3
from decimal import ROUND_HALF_UP, ROUND_HALF_EVEN
from money import card_fee
db = sqlite3.connect("data/finance.sqlite")
rows = db.execute("SELECT id, amount_kobo, fee_kobo FROM transactions WHERE kind='funding_card' AND status='succeeded'").fetchall()
print("successful card fundings:", len(rows))
half_up = [(i, a, f, card_fee(a, ROUND_HALF_UP)) for i, a, f in rows]
half_even = sum(card_fee(a, ROUND_HALF_EVEN) != f for i, a, f in rows)
float_round = sum(min(200_000, round(a * 0.015)) != f for i, a, f in rows)
diff = [r for r in half_up if r[2] != r[3]]
print("half-even disagrees with fee_kobo:", half_even)
print("float round() disagrees with fee_kobo:", float_round)
print("half-up disagrees with fee_kobo:", len(diff))
print("every difference is +1 kobo:", {h - f for i, a, f, h in diff})
print("sum of differences (kobo):", sum(h - f for i, a, f, h in diff))
print("first three:", diff[:3])
ties = sum((a * 15) % 1000 == 500 for i, a, f in rows)
print("exact half-kobo ties:", ties)
print("all amounts whole naira:", all(a % 100 == 0 for i, a, f in rows))
EOFsuccessful card fundings: 10280
half-even disagrees with fee_kobo: 0
float round() disagrees with fee_kobo: 0
half-up disagrees with fee_kobo: 2586
every difference is +1 kobo: {1}
sum of differences (kobo): 2586
first three: [(60, 182300, 2734, 2735), (128, 593500, 8902, 8903), (139, 392300, 5884, 5885)]
exact half-kobo ties: 5152
all amounts whole naira: TrueHalf-even reproduces the ledger on all 10,280 rows. Half-up disagrees on 2,586, each by one kobo, ₦25.86 in total. The first row, transaction 60, is the Predict question: ₦1,823.00 gives 2,734.5, stored as 2,734 and 2,735 under half-up. A tie needs a half kobo, which the whole-naira amounts produce when the naira amount is odd: 5,152 times. The count is of the 10,280 fundings that succeeded; the other 400 of the 10,680 funding_card rows are card declines that never posted, so they have no entries to compare.
4. Find the cap. Find where the uncapped fee first reaches and first exceeds ₦2,000, then count the fundings above it.
python3 - <<'EOF'
import sqlite3
from money import card_fee
db = sqlite3.connect("data/finance.sqlite")
BIG = 10**15 # a cap too large to bite: the uncapped fee
a = 13_333_000
while card_fee(a, cap=BIG) < 200_000: a += 1
print("smallest amount (kobo) whose fee reaches the cap:", a, "=", f"{a // 100}.{a % 100:02d} naira")
b = a
while card_fee(b, cap=BIG) <= 200_000: b += 1
print("first amount whose uncapped fee exceeds the cap:", b)
print("exact break point 200000 / 0.015 =", 200_000 / 0.015, "kobo")
rows = db.execute("SELECT amount_kobo, fee_kobo FROM transactions WHERE kind='funding_card' AND status='succeeded'").fetchall()
capped = [(x, f) for x, f in rows if card_fee(x, cap=BIG) > 200_000]
print("fundings above the cap point:", len(capped))
print("fee_kobo of all of them:", {f for x, f in capped})
print("smallest, largest amount:", min(x for x, f in capped), max(x for x, f in capped))
print("fee given up by the cap (kobo):", sum(card_fee(x, cap=BIG) - 200_000 for x, f in capped))
print("effective rate at the largest:", f"{200_000 / max(x for x, f in capped):.4%}")
EOFsmallest amount (kobo) whose fee reaches the cap: 13333300 = 133333.00 naira
first amount whose uncapped fee exceeds the cap: 13333367
exact break point 200000 / 0.015 = 13333333.333333334 kobo
fundings above the cap point: 31
fee_kobo of all of them: {200000}
smallest, largest amount: 13593500 59211000
fee given up by the cap (kobo): 3119190
effective rate at the largest: 0.3378%The fee reaches the cap at 13,333,300 kobo (₦133,333.00) and rounding alone would push it above the cap from 13,333,367 kobo. The exact break point is 13,333,333.33 kobo. All 31 fundings above it carry exactly 200,000 kobo, the cap gives up 3,119,190 kobo (₦31,191.90) on them, and at ₦592,110.00 the effective rate is 0.3378%.
5. Split a kobo and convert a currency. Run the allocator and the converter on the cases from the chapter.
python3 - <<'EOF'
from decimal import Decimal
from money import allocate, convert, show
print("round each third:", [round(10_000 / 3)] * 3, "sum", sum([round(10_000 / 3)] * 3))
print("allocate 10000 by [1, 1, 1]:", allocate(10_000, [1, 1, 1]))
print("allocate 5 by [70, 30]:", allocate(5, [70, 30]), " by [30, 70]:", allocate(5, [30, 70]))
rate = Decimal("97.25") # illustrative cedi-to-naira rate, not a market rate
lines = [1999, 1999, 1999] # three lines of GH 19.99, in pesewas
each = [convert(x, "GHS", "NGN", rate) for x in lines]
total = convert(sum(lines), "GHS", "NGN", rate)
print("each line in kobo:", each, "-> sum", sum(each))
print("invoice total in kobo:", total, "->", show(total, "NGN"))
print("difference:", sum(each) - total, "kobo")
print("allocate the total by the lines:", allocate(total, lines))
print("JPY 1,000 at 10.1 naira:", show(convert(1000, "JPY", "NGN", Decimal("10.1")), "NGN"))
EOFround each third: [3333, 3333, 3333] sum 9999
allocate 10000 by [1, 1, 1]: [3334, 3333, 3333]
allocate 5 by [70, 30]: [4, 1] by [30, 70]: [2, 3]
each line in kobo: [194403, 194403, 194403] -> sum 583209
invoice total in kobo: 583208 -> 5,832.08 NGN
difference: 1 kobo
allocate the total by the lines: [194403, 194403, 194402]
JPY 1,000 at 10.1 naira: 10,100.00 NGNRounding each third loses a kobo (9,999 against 10,000). Allocation does not. The invoice shows Ogechi’s kobo: lines converted separately sum to ₦5,832.09, the total converted once is ₦5,832.08, and allocating the total across the lines makes them agree at 194,403, 194,403 and 194,402.
Break it. Parse prices the way a quick script would, through a float, and count how often it loses a kobo.
python3 - <<'EOF'
from money import to_minor
bad = []
for k in range(1, 100_000):
price = f"{k // 100}.{k % 100:02d}"
assert to_minor(price, "NGN") == k
if int(float(price) * 100) != k:
bad.append((price, int(float(price) * 100)))
print(f"{len(bad)} of 99,999 prices from 0.01 to 999.99 come out one kobo short with int(float(price) * 100)")
print(bad[:3])
print(f"{to_minor('8.29', 'NGN')} against {int(float('8.29') * 100)}")
EOFYou get 4586 of 99,999 prices from 0.01 to 999.99 come out one kobo short with int(float(price) * 100), the first three being (‘0.29’, 28), (‘0.57’, 56) and (‘0.58’, 57), and 829 against 828 for the price from the chapter. to_minor passes every one of the 99,999. Delete money.py when you are done, or keep it: the module’s project builds on it.
Template
# Money-handling standard: <company or system>
Author (engineering) · Agreed by (finance) · Date · Review: <when this is next checked>
Decision needed: <what the reader is asked to approve, and by when>
## Scope
Applies to: <services, tables, reports, files>. Does not apply to: <for example, third-party files we only read>.
## Storing
- Amounts are integers of <minor unit>, never floats. Column names carry the unit: <amount_kobo>.
- Every amount has a currency code beside it: <currency field name>. An amount without one is a bug.
- The exponent for each currency lives in one table: <where>. Never a hard-coded 100.
## Rounding
- Rule: <mode by name>, applied to <which calculations>.
- Rounding happens once, at <which step>, after the whole calculation.
- Input with more decimals than the currency allows is <rejected, not rounded>.
## Splitting and converting
- Splits use <method>; the leftover unit goes to <who>; ties are broken by <stable order>.
- Conversion: convert the <total or line> once, allocate to the lines, and store the rate (<type>) and its <source and date>.
## Displaying
- Screens and invoices: <format, for example symbol, thousands separator, decimals from the exponent>.
- Files for other systems: <format>. Display text is never parsed back into money.
## Forbidden
- <Practice>, because <what it breaks>.
## Where does the kobo go (worked example)
<A calculation where a rounding or a split leaves a kobo, showing each step and where the kobo ends up.>
## Code-review checklist
- [ ] <Check a reviewer can answer yes or no from the diff>
## Disputes
When our figure and a counterparty's differ by <amount>: <whose rule wins, who decides>. WORKED EXAMPLE
At Wrenpost, Folarin, who owns the billing code, writes the standard. Ogechi agrees it for finance and signs it; from then on a reviewer holds every pull request that touches money to its checklist.
Money-handling standard: Wrenpost billing. Author Folarin · Agreed by Ogechi · 19 November 2026 · Review: when a new currency is added.
Decision needed: approve this as the rule reviewers enforce on billing code from the next release. Scope: invoice and ledger code and the month-end report; not provider files we only read.
Core rules: store integer minor units with a currency code; take exponents from one table; reject input with too many decimals; round half even, once, at the end of a calculation; convert an invoice total once and allocate it to its lines by largest remainder, with ties going to the earlier line. Forbidden: floats, because they drift; a hard-coded 100, because it is wrong for yen; rounding each share, because the shares stop adding up.
Where does the kobo go. An invoice has three lines of GH₵19.99, which is 1,999 pesewas each, at the lab’s illustrative rate of 97.25 naira to the cedi.
- Each line converted alone is 194,402.75 kobo, which rounds to 194,403. Three lines sum to 583,209 kobo.
- The total, 5,997 pesewas, converted once is 583,208.25 kobo, which rounds to 583,208.
- The two routes differ by 1 kobo: ₦5,832.09 against ₦5,832.08.
- The customer pays the total, so the total wins. Allocating 583,208 across the lines gives 194,403, 194,403 and 194,402. The kobo that does not exist goes off the third line, because the tie-break is line order.
Review checklist item: does any * 100, / 100 or float touch an amount? Does a converted line total come from allocation rather than from rounding each line?
How it could be wrong: the invoice total is not always what the customer is charged. If a contract bills per line, the rule changes. A month of invoices that do not sum to their totals would show it.
Now you
A month later, Owoleaf’s wallet team is about to connect a second card processor, and you have been asked to write the wallet’s money standard before it goes live. The processor’s documentation does not say how it rounds card fees, and that is a risk the standard has to cover.
Use the lab. Half even reproduces fee_kobo on all 10,280 successful card fundings. Half up disagrees on 2,586 of them, each by 1 kobo, ₦25.86 in total. The fee is capped at 200,000 kobo, and 5,152 fundings are exact half-kobo ties. The ₦100.00 split three ways gives 3,334, 3,333 and 3,333. State any figure the lab does not show as an assumption, such as that the wallet holds naira only.
Write the standard, including a worked example and a short dispute rule for when the processor’s figure differs by 1 kobo. Owoleaf’s head of engineering would read it, and its finance controller would sign it. It supports one decision: whether the standard is the rule reviewers enforce from the day the processor goes live.
Self-check
Wrenpost's billing team has to settle a rule now. Invoices in four currencies are converted to naira for the ledger, about 2,400 a month if each business customer gets one. Folarin proposes rounding each invoice line to the kobo after conversion; Ogechi proposes converting the invoice total once and allocating it to the lines. Which rule goes in the billing code?
- DOC ISO 4217: Currency codes ISO
The standard behind currency codes and minor units, and the page that names its maintenance agency. Read the overview; the exponent for each currency is in the agency's published list, which you should check before copying a table into code.
- BOOK Money Martin Fowler, 2002
The short catalogue entry behind the chapter's rule that an amount is an integer and a currency together. The allocation detail is in the book's code; this page could not be opened while the chapter was written, so check it says what the chapter describes. Read: Patterns of Enterprise Application Architecture, the Money pattern: why an amount is a quantity plus a currency, and allocation without losing a unit.
- DOC decimal: Decimal fixed-point and floating-point arithmetic Python documentation
The rounding modes by name, how to construct a Decimal from a string and why not from a float, and the default context. Read the rounding modes and the quantize method; skip the thread and signal sections.
- PAPER What every computer scientist should know about floating-point arithmetic David Goldberg, 1991
The standard explanation of why 0.1 has no exact binary form and how rounding error accumulates. Read the first two sections for the mechanism; skip the proofs. Read: ACM Computing Surveys 23(1), sections 1 and 2 on representation and rounding error.
- DOC General Decimal Arithmetic Specification Mike Cowlishaw, 2009
The specification Python's decimal module follows, with the definition of each rounding mode. Read the rounding section to see half up and half even stated precisely; skip the conversion and exception details.
- DOC Supported currencies Stripe (a vendor's documentation)
One payment API's own table of zero-decimal currencies and its exceptions, such as ISK and UGX. Read it to see how a provider's convention can differ from the standard; the list changes, so check the page rather than this summary.
- DOC Legal tender Central Bank of Nigeria
The central bank's own legal tender page, with images of the naira's notes and coins. Look at which kobo coins it shows, since other sources disagree about which are current; this page could not be opened while the chapter was written.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.