brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's decimal.Decimal keeps money sums exact

Python
~/tips/tip-python-decimal-for-money

from decimal import Decimal, ROUND_HALF_UP

Add up prices and amounts without floating point rounding errors.

Floats are fine for measurements, but I don’t want them anywhere near an invoice total. Python’s decimal module does base ten maths the way you learned it at school.

from decimal import Decimal, ROUND_HALF_UP

print(0.1 + 0.2)                                # 0.30000000000000004
print(Decimal("0.10") + Decimal("0.20"))        # 0.30

price = Decimal("19.99") * 3 * Decimal("1.21")
print(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))   # 72.56

Decimals keep their digits exactly and even remember trailing zeros, so 0.30 stays 0.30. quantize rounds to cents, and you choose the rounding rule yourself. ROUND_HALF_UP is what most people expect on a receipt. The default is banker’s rounding, which rounds a half to the nearest even digit.

Create them from strings, never from floats. Decimal(0.1) gives you the float’s real value, a long string ending in ...5625, because the error was already there before Decimal saw it. Reading amounts straight from a CSV or JSON as text and passing that text in avoids the problem.

They’re slower than floats and you can’t mix them with floats in maths, which raises a TypeError. I see that as a feature: it forces you to decide on purpose.

Further reading: decimal module

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link