Full answer
from decimal import Decimal, ROUND_HALF_UP, getcontext
PAISA = Decimal("0.01")
def money(x):
return Decimal(x).quantize(PAISA, rounding=ROUND_HALF_UP)
lines = [("Notebook", Decimal("45.50"), 3), ("Pen", Decimal("9.99"), 7)]
gst = Decimal("0.18")
subtotal = sum((price * qty for _, price, qty in lines), Decimal("0"))
per_line = sum(money(price * qty * gst) for _, price, qty in lines)
on_total = money(subtotal * gst)
print(subtotal, per_line, on_total)
f = 0.0
for _ in range(10):
f += 0.1
print(f, sum([Decimal("0.1")] * 10))
print(getcontext().prec)Output:
206.43 37.16 37.16
0.9999999999999999 1.0
28The subtotal is exactly 206.43. Rounding tax per line gives 37.16, while rounding once on the total gives 37.16 as well here, but the two methods can differ by a paisa on other baskets, so the invoice rule must be chosen explicitly and applied consistently. Adding 0.1 ten times in a float loop gives 0.9999999999999999, while Decimals sum to exactly 1.0. (The built-in sum uses compensated summation since Python 3.12 and would print 1.0 for floats, which hides the error rather than removing it.) The default Decimal context has 28 significant digits, ample for currency. Passing Decimal(x) a float would import its binary error, which is why money receives Decimals or strings.
from decimal import Decimal, ROUND_HALF_UP, getcontext
PAISA = Decimal("0.01")
def money(x):
return Decimal(x).quantize(PAISA, rounding=ROUND_HALF_UP)
lines = [("Notebook", Decimal("45.50"), 3), ("Pen", Decimal("9.99"), 7)]
gst = Decimal("0.18")
subtotal = sum((price * qty for _, price, qty in lines), Decimal("0"))
per_line = sum(money(price * qty * gst) for _, price, qty in lines)
on_total = money(subtotal * gst)
print(subtotal, per_line, on_total)
f = 0.0
for _ in range(10):
f += 0.1
print(f, sum([Decimal("0.1")] * 10))
print(getcontext().prec)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Decimal from strings or integer paise
- Explicit rounding mode
- Decide per-line or total tax rounding
- Centralise rounding
- Floats accumulate errors
Common mistakes
- Using float for money
- Rounding at different points in different code paths
Follow-ups
- How would you split a payment into three equal parts?
- How should money be stored in a database?
Tips
- Show float versus Decimal