Financial calculations
Money, invoices, tax, and prices where decimal rounding must be explicit.
Python · Module
Python’s decimal module provides correctly rounded decimal arithmetic with configurable precision, rounding, exponent limits, and signal handling. It is designed for exact decimal-style and controlled rounded calculations.
The module represents decimal values independently of binary floating-point and performs arithmetic under a context. The context controls precision, rounding, exponent limits, and which signals become exceptions; localcontext() temporarily changes those settings for a block.
from decimal import Decimal, getcontext, localcontext
Decimal(value)
getcontext()
localcontext(ctx=None)| Name | Type | Description |
|---|---|---|
value | int | str | tuple | float | A value accepted by Decimal, commonly an integer, string, tuple, or float. |
c | Context | The active arithmetic context used by context functions and operations. |
Decimal operations return new Decimal objects; getcontext() returns the current Context and setcontext() changes the active Context.
from decimal import Decimal, getcontext, localcontext
getcontext().prec = 6
amount = Decimal("1.20")
rate = Decimal("0.075")
with localcontext() as ctx:
ctx.prec = 10
total = amount * (Decimal("1") + rate)
print(total) # 1.2900Construct Decimal values from strings, use the current context for normal arithmetic, and temporarily increase precision inside localcontext().
Money, invoices, tax, and prices where decimal rounding must be explicit.
Measurements or algorithms requiring more configurable precision than binary float provides.
Operations where rounding, overflow, invalid operations, or division by zero must be monitored.
Decimal provides decimal floating-point arithmetic with user-adjustable precision, unlike binary float arithmetic. It is useful when decimal representation and rounding behavior matter, such as accounting calculations.
Follow-up: How should Decimal values be constructed from user input? Construct them from decimal strings or integers, avoiding float inputs when the intended value is a decimal quantity.
A context is the arithmetic environment for Decimal operations. It controls precision, rounding, exponent limits, and which signals are trapped as exceptions.
Follow-up: How can one change settings without affecting surrounding code? Use localcontext() as a context manager, then modify the copied context inside the block.
Decimal objects are immutable, so operations create new Decimal results rather than modifying their operands. Their representation retains significant trailing zeros supplied during construction.
Follow-up: What does precision mean for an existing Decimal? Context precision limits arithmetic results, not the digits already stored in a Decimal object.
DecimalContextgetcontext()setcontext()localcontext()ROUND_HALF_EVENInvalidOperationDivisionByZero