Hone

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 + 20
Cents: exact.
print(total / 100)
0.3: divide only to display.
from decimal import Decimal
Exact 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 * ))

The trap

Decimal(0.1) is not 0.1: it is the float's exact binary value. Build Decimals from strings, Decimal('0.1').

Practise money is whole cents on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.