Numbers, Decimals, and Precision
On this page
Numeric Types in Real Systems
int is exact. float is approximate. For money and billing, use Decimal with explicit rounding.
Float Surprise
print(0.1 + 0.2) # 0.30000000000000004
Decimal for Money
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.99")
tax_rate = Decimal("0.20")
total = (price * (Decimal("1") + tax_rate)).quantize(
Decimal("0.01"),
rounding=ROUND_HALF_UP,
)
Operational Checklist
- No floats in money paths (pricing, invoices, payouts).
- Rounding policy is defined and tested.
- Units are explicit in code and configs (seconds vs milliseconds).
Failure Modes
- Precision drift: small errors accumulate across computations.
- Implicit casts: mixing int/float silently changes results.