Lessons · Python · money is whole cents
Money is whole cents
Floats cannot hold 0.1 exactly, so sums of prices drift. Store money as integer cents (or Decimal) and format to whole units only for display.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
An invoice that is one cent off fails reconciliation and gets a human phone call. Thousands of floating-point additions turn a rounding error into real money.
How to think about it
Decide the unit once: the smallest one, as an integer. Add and multiply in that unit; divide by 100 only when printing. When you need fractions of a cent, use decimal.Decimal, never float.
Worked example
print(0.1 + 0.2)0.30000000000000004: the float error, visible on the first sum.
total = 10 + 20Cents: exact.
print(total / 100)0.3: divide only to display.
from decimal import DecimalExact decimals when you need them.
print(Decimal("0.10") + Decimal("0.20"))0.30: Decimal built from strings is exact too.Your turn
Add a line to an order kept in cents.
total_cents += int(round(price * ))
Solve one with the tests running
The trap
Decimal(0.1) is not 0.1: it is the float's exact binary value. Build Decimals from strings, Decimal('0.1').