Calculate Decimal Totals
Core idea
Use Decimal("...") for decimal input text, especially amounts with defined decimal precision. Arithmetic uses a context with precision and rounding settings; even Decimal division may round. quantize rounds to the exponent of its argument.
from decimal import Decimalprint(Decimal("0.10") + Decimal("0.20"))String construction avoids converting an already rounded binary float.
Apply a rounding rule
from decimal import Decimal, ROUND_HALF_UPprint(Decimal("2.345").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))The result has two decimal places; ties round away from zero under this policy.
Limit precision locally
from decimal import Decimal, localcontextwith localcontext() as ctx: ctx.prec = 4 print(Decimal(1) / Decimal(3))The with block (a context manager, covered in a later chapter) temporarily applies four significant digits and restores the previous context on exit.
Common mistake
Decimal(0.1) preserves the binary float approximation rather than the intended decimal tenth. Do not mix floats into Decimal arithmetic; choose a rounding policy appropriate to the domain.
Practice
Sum three amounts supplied as strings and quantize once at the end to two places using ROUND_HALF_UP.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Decimal rounding
Check your understanding of decimal.
What is printed?
from decimal import Decimalprint(Decimal("0.40") + Decimal("0.20"))What is printed?
from decimal import Decimal, ROUND_HALF_UPprint(Decimal("-1.245").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))What is printed?
from decimal import Decimal, localcontextwith localcontext() as ctx: ctx.prec = 3 print(Decimal(1)/Decimal(7))Which construction best preserves decimal input text 0.1?