Decimal represents base-ten values with an arithmetic context rather than inheriting binary floating-point approximation.
Python Decimal money: parse decimal text and choose rounding explicitly
Operation contract
The invoice fixture constructs Decimal from text and quantizes to two places with ROUND_HALF_UP. It separately rejects non-finite values. Decimal("12.345") rounds to 12.35 under that stated policy; converting a binary float first could carry its earlier approximation into the decimal object.
Failure and ownership boundary
Rounding is a domain decision. A tax calculation may require another policy or round at another stage. Decimal does not supply currency identity, input length limits, positive-value rules or unlimited arithmetic precision. The local context pins working precision for the bounded example. Python input exercise: accept an explicit integer grammar and Java BigDecimal: decimal amounts and explicit rounding address comparable choices.
Working program
from decimal import Decimal, localcontext, ROUND_HALF_UP
def invoice_amount(text):
if len(text) > 24:
raise ValueError("amount too long")
with localcontext() as context:
context.prec = 28
amount = Decimal(text)
if not amount.is_finite():
raise ValueError("finite amount required")
return amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(invoice_amount("12.345"))
try:
invoice_amount("NaN")
except ValueError:
print("non-finite amount rejected")Output
12.35
non-finite amount rejectedCosts and limits
Decimal work depends on retained digits and precision. This fixture caps textual length and context precision; it does not define every currency’s minor-unit or maximum amount rule.
Common Mistakes
- Construct exact decimal input from text.
- Do not leave rounding policy implicit.
Connected lessons
Python functions: define units, validate input and return a result, Python input exercise: accept an explicit integer grammar, Java BigDecimal: decimal amounts and explicit rounding.
Apply this boundary
NumPy broadcasting: declare axes and bound integer arithmetic, Pandas nullable integers: missing amounts are not zero.
Follow the ownership and update boundary
Python Fraction: exact ratios require an exact input representation.
Follow the integrity boundary
Python Decimal Inexact trap: reject fractional minor units.
Continue with Python amount parsing: define a wire format before Decimal.
Continue with Python decimal localcontext: keep a rounding rule inside one calculation.
