Python Decimal.quantize
Decimal.quantize rounds a decimal number to the exponent of another Decimal. Supplying the rounding mode makes the treatment of ties explicit.
A simple example
Decimal.quantize
- Start with 1.234
- Do this Round to two decimal places
- Result 1.23
Syntax
amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Round invoice lines to a currency unit
An invoice printer must turn line prices into a reproducible money total. Decide where rounding happens and which unit the accumulator stores before comparing the printed invoice with the ledger.
from decimal import Decimal, ROUND_HALF_EVEN
cent = Decimal("0.01")
for price in ("2.005", "2.015"):
print(Decimal(price).quantize(cent, rounding=ROUND_HALF_EVEN))
2.00 2.02
Read exact decimal inputs from strings. Constructing Decimal from a binary float also preserves the float's approximation, which can change whether a value is an exact tie.
Python documentation for Decimal.quantize
Round a parcel reading for a whole-unit display
A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.
The reading lies closer to nineteen than eighteen.
Show a quiet hour on a dashboard
A sensor dashboard rounds the average number of entries to a whole count. This hour’s average is 6.2 so the designer checks what visitors will see.
The fraction is below one half, so the displayed whole count is six.