The Decimal Inexact signal records a rounding operation that discards nonzero digits.
Python Decimal Inexact trap: reject fractional minor units
Operation contract
The amount parser accepts short decimal strings, checks finiteness and nonnegativity, then uses a local context with an Inexact trap while quantizing to two places. A cent-exact input becomes integer minor units. An amount with three nonzero fractional places fails instead of being rounded silently. The local context keeps this choice out of unrelated decimal work.
Failure and ownership boundary
Inexact differs from Rounded: dropping a trailing zero may set Rounded without losing value. Construct Decimal from the input string, not a binary float. Currency-specific scale and limits still belong to the application contract. Python Decimal money: parse decimal text and choose rounding explicitly, Python Fraction: exact ratios require an exact input representation and Python quantiles: choose an interpolation policy before reporting a threshold give other representations.
Working program
from decimal import Decimal, Inexact, InvalidOperation, localcontext
def minor_units(text):
if type(text) is not str or not 1 <= len(text) <= 12:
raise ValueError("amount length")
try:
value = Decimal(text)
if not value.is_finite() or not 0 <= value <= 10000:
raise ValueError("amount range")
with localcontext() as context:
context.traps[Inexact] = True
cents = value.quantize(Decimal("0.01"))
return int(cents * 100)
except (InvalidOperation, Inexact) as cause:
raise ValueError("fractional minor unit") from cause
print(minor_units("12.50"))
print(minor_units("12.500"))
try:
minor_units("12.501")
except ValueError:
print("fractional cent rejected")Output
1250
1250
fractional cent rejectedCosts and limits
The fixture bounds input length and amount magnitude. Decimal operation cost still depends on coefficient digits and context precision; a real money parser must also choose an explicit currency scale.
Common Mistakes
- Inexact and Rounded are different signals.
- Creating Decimal from float imports a binary approximation.
Connected lessons
Python Decimal money: parse decimal text and choose rounding explicitly, Python Fraction: exact ratios require an exact input representation, Python quantiles: choose an interpolation policy before reporting a threshold.
