Decimal arithmetic and rounding policy
An invoice contains three items priced at 0.335 each. You must display a two-place total. Before choosing a rounding function, ask whether the rule applies to each line or to the final sum.
On this page
Preserve the input
Read decimal quantities from text with Decimal. A binary float is already an approximation for many decimal fractions. Converting that float later preserves its binary approximation. Constructing Decimal directly from the original text preserves the specified decimal value.
Compare two valid calculations
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("0.335")
cent = Decimal("0.01")
def cents(value):
return value.quantize(cent, rounding=ROUND_HALF_UP)
print(cents(price) * 3)
print(cents(price * 3))The first calculation rounds one price to 0.34, then multiplies by three to produce 1.02. The second multiplies exactly to 1.005 before rounding once to 1.01. Both use identical inputs and the same rounding mode. The point at which rounding occurs changes the result.
Test the policy boundary
If the specification says to round each line independently, use the first calculation for three separate lines. If it says to round the invoice total, use the second. Record that rule in a test whose expected value is written independently of the implementation. Try 0.334 as well. Rounding the line now gives 0.33, and three lines give 0.99. The unrounded sum is 1.002, which rounds to 1.00.