Syntax
Decimal("1.25").quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)Examples
Decimal Arithmetic and Rounding
Run as a Python 3.11+ script.
from decimal import Decimal, ROUND_HALF_UP
subtotal = Decimal("0.10") + Decimal("0.20")
rounded = Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(subtotal)
print(rounded)- Expected output: 0.30 2.35
- quantize specifies a target exponent and explicit rounding rule. Decimal arithmetic still has a context precision; it is not infinitely precise for every operation.
Best practices
- Keep monetary inputs as strings or integer minor units before conversion.
- Document the rounding rule and the stage at which rounding occurs.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference