Money and Decimal
Revenue, fees, payouts, advances: a lot of interview tasks are about money. The interviewer checks three things early. Is the money a Decimal? Is it rounded to cents with an explicit mode? Do the parts add up to the total? A float in the chain or a lost cent in a split is the kind of bug that stays hidden until finance finds it.
Why not float
Section titled “Why not float”from decimal import Decimal
print(0.1 + 0.2 == 0.3, 0.1 + 0.2) # False 0.30000000000000004print(sum([0.10] * 3)) # 0.30000000000000004print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
print(Decimal(0.1)) # 0.1000000000000000055511151231257827021181583404541015625print(Decimal(str(0.1))) # 0.1print(Decimal("9.99") * 3, Decimal("10.00") == Decimal("10")) # 29.97 TrueA float is a binary fraction. Most decimal amounts, such as 0.1, have no exact binary form, so every float amount is a little off, and sums make the error visible. Decimal stores decimal digits, so 0.1 is exactly 0.1.
Create a Decimal from a string. Decimal(0.1) copies the float exactly, with its binary error. If the value is already a float, go through str(). Mixing the two types in arithmetic fails loudly, which is good: Decimal("1.10") + 0.1 raises TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'. A comparison does not fail: Decimal("0.1") == 0.1 is False, with no error, because the float holds a value slightly above 0.1. So a check like amount == expected can be wrong, and nothing tells you. Mixing with int is fine: Decimal("9.99") * 3 is Decimal('29.97').
A Decimal keeps its trailing zeros: Decimal("10.00") and Decimal("10") are equal, but they print differently. Tests that compare values do not care; a report that prints them might.
Why not float for money? How do you round to cents?
Say your answer out loud first, then open it.
Show the answer
“Float is binary, so 0.1 + 0.2 is not exactly 0.3, and the error grows in sums. I use Decimal created from strings, and quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) for cents. In the database it is NUMERIC(12, 2).”
round() on a Decimal is banker’s rounding: 0.125 → 0.12.
Rounding to cents
Section titled “Rounding to cents”from decimal import Decimal, ROUND_HALF_UP, ROUND_DOWN
CENT = Decimal("0.01")for s in ("0.125", "0.135", "2.675", "23.9976"): x = Decimal(s) print(s, x.quantize(CENT, rounding=ROUND_HALF_UP), round(x, 2), x.quantize(CENT), # no rounding=: the context default x.quantize(CENT, rounding=ROUND_DOWN))
print(round(2.675, 2)) # 2.67 -- a float: 2.675 is stored as slightly less| Value | quantize, ROUND_HALF_UP | round(x, 2) | quantize, no mode | quantize, ROUND_DOWN |
|---|---|---|---|---|
0.125 | 0.13 | 0.12 | 0.12 | 0.12 |
0.135 | 0.14 | 0.14 | 0.14 | 0.13 |
2.675 | 2.68 | 2.68 | 2.68 | 2.67 |
23.9976 | 24.00 | 24.00 | 24.00 | 23.99 |
quantize(Decimal("0.01")) means “round to the same exponent as 0.01”, that is, to cents. Without rounding=, it uses the mode of the current context, which is ROUND_HALF_EVEN by default: a half goes to the even digit. round(x, 2) on a Decimal does the same, so 0.125 becomes 0.12 with both. Half up is what people expect from a receipt, so always pass rounding=ROUND_HALF_UP and say why. Use ROUND_DOWN when the amount is a limit that must never be exceeded.
The last line shows why the input must be a Decimal before rounding: as a float, 2.675 is stored as slightly less, and round gives 2.67.
Where to round
Section titled “Where to round”fee = Decimal("9.99") * Decimal("0.15")print(fee, fee.quantize(CENT, rounding=ROUND_HALF_UP)) # 1.4985 1.50
lines = [Decimal("0.125")] * 3per_line = sum(x.quantize(CENT, rounding=ROUND_HALF_UP) for x in lines)at_end = sum(lines).quantize(CENT, rounding=ROUND_HALF_UP)print(per_line, at_end) # 0.39 0.38
print(Decimal("100") / 3) # 33.33333333333333333333333333 -- 28 significant digitsprint(Decimal(-7) // 2, -7 // 2) # -3 -4 -- Decimal // goes toward zero, int // goes downMultiplication keeps all digits: a 15% fee on 9.99 is 1.4985. Rounding each line and rounding the total give different answers: 0.39 and 0.38 here. Ask which one the task wants: “Do we round each line or only the total?” Division gives 28 significant digits by default, so round the result before you store or compare it.
Splitting an amount in cents
Section titled “Splitting an amount in cents”100.00 split three ways cannot be three equal amounts in cents. Rounding each part on its own loses a cent:
amount, n = Decimal("100.00"), 3
naive = [(amount / n).quantize(CENT, rounding=ROUND_HALF_UP)] * nprint(naive, sum(naive)) # [Decimal('33.33'), Decimal('33.33'), Decimal('33.33')] 99.99
cents = int(amount * 100) # 10000base, rest = divmod(cents, n) # 3333 cents each, 1 cent left overprint(base, rest) # 3333 1divmod(a, b) returns the quotient and the remainder at once. Work in whole cents: every part gets base cents, and the first rest parts get one cent more. Then the parts differ by at most one cent and always add up to the original amount. int(amount * 100) drops anything below a cent, so quantize the amount first if it can have more digits.
Allocating a payout oldest first
Section titled “Allocating a payout oldest first”A marketplace payout arrives, and the merchant has open debts, such as advances, oldest first. The rule fits in one sentence: “Each debt gets min(what is left, what is due), and I stop when nothing is left.” With debts d1 = 30.00 and d2 = 50.00:
| Payout | Payments | Left for the merchant |
|---|---|---|
0.00 | none | 0.00 |
20.00 | d1 20.00 | 0.00 |
30.00 | d1 30.00 | 0.00 |
45.00 | d1 30.00, d2 15.00 | 0.00 |
100.00 | d1 30.00, d2 50.00 | 20.00 |
-5.00 | ValueError | — |
Each row is an edge case to test before you say “done”: zero, a partial payment, exactly on a boundary, more than all debts, and bad input. Three mistakes show up again and again:
- A zero line. Without
if pay > 0(or abreakwhenleft == 0), the30.00payout also records('d2', Decimal('0.00')). - Only whole debts. Every cent of the payout goes to the debt first. Paying only the debts that fit completely sends money to the merchant while a debt is still open.
- A loop around the loop.
while left > 0:around theforpaysd1a second time when the payout is larger than all debts. One pass over the sorted debts and abreakis enough.
Practice
Section titled “Practice”Split an amount (Decimal, cents) into n parts that sum exactly to the amount and differ by at most 0.01; bigger parts first. Each part is a Decimal with two decimals, such as Decimal('10.00').
Data and an example
The checks run after your code and can use these:
from decimal import Decimal as DExample: split_amount(D('100.00'), 3) → [D('33.34'), D('33.33'), D('33.33')]
5 checks. Your own print() output is shown too.
from decimal import Decimal
def split_amount(amount, n):
...
Show answer
Reference
from decimal import Decimal
def split_amount(amount, n): cents = int(amount * 100) base, rest = divmod(cents, n) # scaleb(-2) turns cents into dollars and keeps two decimals: 1000 -> Decimal('10.00') return [Decimal(base + (1 if i < rest else 0)).scaleb(-2) for i in range(n)]Checks and the expected values
-
split_amount(D('100.00'), 3)→[Decimal('33.34'), Decimal('33.33'), Decimal('33.33')] -
split_amount(D('0.05'), 2)→[Decimal('0.03'), Decimal('0.02')] -
split_amount(D('10.00'), 7)→[Decimal('1.43'), Decimal('1.43'), Decimal('1.43'), Decimal('1.43'), Decimal('1.43'), Decimal('1.43'), Decimal('1.42')] -
sum(split_amount(D('10.00'), 7))→Decimal('10.00') -
split_amount(D('20.00'), 2)→[Decimal('10.00'), Decimal('10.00')]
Money is divided in whole cents. divmod(cents, n) gives the base and the remainder, and the remainder goes one cent at a time to the first parts. Rounding each part on its own does not work: the sum would differ from the original amount by a cent. Putting the whole remainder on one part does not work either: the third check splits 10.00 into 7 and expects six parts of 1.43, not one part of 1.48. The fourth check tests the sum. Turn cents back into money with scaleb(-2) or * Decimal("0.01"): Decimal(1000) / 100 is Decimal('10'), and the last check expects Decimal('10.00').
A payout arrives. Debts are (debt_id, amount_due) oldest first. Pay them in order, partially if money runs out. Return (payments, left_for_merchant), payments as (debt_id, paid) without zero lines. A negative payout raises ValueError.
Data and an example
The checks run after your code and can use these:
from decimal import Decimal as DDEBTS = [("a1", D("102.50")), ("a2", D("200.00"))]Example: pay_oldest_first(D('150.00'), DEBTS) → ([('a1', D('102.50')), ('a2', D('47.50'))], D('0.00'))
5 checks. Your own print() output is shown too.
from decimal import Decimal
def pay_oldest_first(payout, debts):
...
Show answer
Reference
from decimal import Decimal
def pay_oldest_first(payout, debts): if payout < 0: raise ValueError("negative payout") left = payout payments = [] for debt_id, due in debts: if left == 0: break pay = min(left, due) if pay > 0: payments.append((debt_id, pay)) left -= pay return payments, leftChecks and the expected values
-
pay_oldest_first(D('150.00'), DEBTS)→([('a1', Decimal('102.50')), ('a2', Decimal('47.50'))], Decimal('0.00')) -
pay_oldest_first(D('102.50'), DEBTS)→([('a1', Decimal('102.50'))], Decimal('0.00')) -
pay_oldest_first(D('400.00'), DEBTS)→([('a1', Decimal('102.50')), ('a2', Decimal('200.00'))], Decimal('97.50')) -
pay_oldest_first(D('0'), DEBTS)→([], Decimal('0')) -
pay_oldest_first(D('-1'), DEBTS)→raises ValueError
The rule in one sentence: “each debt gets min(what is left, what is due); stop when the money runs out”. Do not write zero lines: if pay > 0. The checks are the edge cases: a partial payment, exactly on a boundary, more than all debts, zero, and a negative payout that raises ValueError.
Further reading
Section titled “Further reading”- decimal: quick-start tutorial — creating values, the context and its default precision.
- Decimal.quantize and rounding modes —
ROUND_HALF_UP,ROUND_HALF_EVEN,ROUND_DOWN. - decimal FAQ — the recipe for “two decimal places”.
- Floating-point arithmetic: issues and limitations — why
0.1 + 0.2is not0.3. - divmod() — quotient and remainder in one call.
- PostgreSQL: arbitrary precision numbers —
NUMERIC(precision, scale)for money.
Related topics
Section titled “Related topics”- Errors and validation — turning an input string into a
Decimalsafely. - dict, defaultdict and Counter — totals per key with
defaultdict(Decimal). - Money and ledgers — the same money in SQL: flows, balances and ledgers.
- Money tasks — advances, matching payments and safe payouts as full tasks.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.