Money and units in code: whole cents, whole grams, no floating point
Why 0.1 + 0.2 isn't 0.3, how to store money and measurements as integers, and how to round up and round half up with integer arithmetic only.
Every business program handles quantities: prices, weights, distances, durations. Getting them exactly right is mostly about one decision: what unit, and what type?
Floats are not decimals
Try this in Python:
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.1 + 0.1 == 0.3
FalseThat's not a Python bug. A float stores numbers as binary fractions, and 0.1 has no exact binary
form, the same way 1/3 has no exact decimal form (0.333...). The error is tiny, but it's there,
and it grows when you add thousands of amounts, compare totals, or round.
For measurements in science, that's fine. For money, where an invoice must match to the cent, it isn't.
Money in whole cents
Choose the smallest unit you care about and count it with integers:
| Quantity | Store as | Example |
|---|---|---|
| Price | cents (int) | 4.90 € → 490 |
| Weight | grams (int) | 2.5 kg → 2500 |
| Length | millimetres | 1.2 m → 1200 |
| Duration | seconds or ms | 1.5 min → 90 |
Integers add, subtract, multiply and compare exactly. You convert to "4.90" only when showing the value to a person:
def format_cents(cents: int) -> str:
euros, rest = divmod(abs(cents), 100)
sign = "-" if cents < 0 else ""
return f"{sign}{euros}.{rest:02d}"And when reading what people type, parse the text directly into the small unit. Never go through
float("2.5"):
match = re.fullmatch(r"([0-9]+)(?:[.,]([0-9]{1,3}))?", text)
kilos, fraction = match.groups()
grams = int(kilos) * 1000 + int((fraction or "").ljust(3, "0")) # "2,5" -> 2500Round up without floats
Rules like "every started kilogram costs 0.60" or "volume / 5, rounded up" are ceiling
divisions. The tempting way is math.ceil(a / b), but / produces a float. Stay in integers:
def ceil_div(a: int, b: int) -> int:
return -(-a // b) # or (a + b - 1) // b, for a >= 0 and b > 0
ceil_div(5200 - 5000, 1000) # 1 started kilogram
ceil_div(6000 - 5000, 1000) # 1
ceil_div(6001 - 5000, 1000) # 2Why does -(-a // b) work? // rounds down (towards minus infinity). Negating, rounding down,
and negating again rounds up.
Round half up
Percentages create fractions of a cent. 19% VAT on 10.50 € is 199.5 cents. The usual business rule is half up: .5 and above go up.
def percent_of(cents: int, percent: int) -> int:
return (cents * percent + 50) // 100 # half up, for non-negative amounts
percent_of(1050, 19) # 200: 199.5 rounded up
percent_of(1530, 50) # 765Don't use Python's round() for this: it rounds halves to the nearest even number
(round(0.5) is 0, round(2.5) is 2). That's called banker's rounding, and it's not what most
invoices expect.
Round once, in one place
Every rounding step can lose up to half a unit. Round as late as possible, ideally once per amount that's shown to someone, and write the rounding rule in one function so it's the same everywhere. Then test it on an exact half.
Questions and answers
- Why shouldn't I use float for money?
- Floats are binary fractions, and most decimal amounts like 0.10 have no exact binary form. Small errors appear and add up: 0.1 + 0.2 is 0.30000000000000004. Store whole cents in an integer, or use a decimal type, and the arithmetic is exact.
- How do I round up an integer division?
- Use (a + b - 1) // b, or -(-a // b) in Python, for non-negative numbers. Both are exact for any size, unlike math.ceil(a / b), which goes through a float.
Read next
- Validating input: check once at the boundary, then trust your types
Where to validate data, how to report every problem at once with field paths, and how to write error messages people can act on. With examples in Python.