decimal when exact decimal precision matters
decimal gives you exact decimal arithmetic, which is often a better fit than float when precision and rounding rules matter.
Why it is useful
Floating-point arithmetic can surprise people:
print(0.1 + 0.2)
With Decimal, you get exact decimal semantics:
from decimal import Decimal
total = Decimal("0.1") + Decimal("0.2")
print(total)
Output:
0.3
Good use cases
- money values
- invoices and totals
- explicit rounding rules
- domains where decimal precision matters
One important detail
Create Decimal values from strings when precision matters. Starting from a float can carry float imprecision into the result.
Rules of thumb
- Use
decimalwhen exact decimal behavior matters. - Create
Decimalvalues from strings. - Prefer
floatonly when approximate numeric work is acceptable.