Quantize a Decimal amount to two minor units

A two-decimal display format alone does not establish a monetary rounding rule. Decimal.quantize() changes a Decimal to the exponent supplied by its second Decimal argument. Here, Decimal("0.01") specifies two digits after the decimal point, and ROUND_HALF_UP makes the tie value 12.345 become 12.35. The program asserts both the resulting numeric value and its fixed two-place presentation.

Passing the rounding mode directly makes the example's policy visible instead of relying on the active decimal context. That matters because a process can use a different context rounding mode elsewhere. ROUND_HALF_UP is only one possible policy; some domains require half-even, truncation, cash increments, or currency-specific rules. Select the policy from the actual requirement rather than treating this result as universal.

Construct Decimal values from decimal strings in this kind of input path. Constructing from a binary float captures the float's exact binary approximation, which can make a boundary value surprising. quantize() can signal or raise exceptions under some contexts, including when the result cannot fit the context precision, so callers should define error handling for their data range. The assertions verify this one positive input and chosen rule, not external validation or compliance.

quantize() is part of the Python standard-library decimal module and is available in supported Python 3 releases. See the official Decimal.quantize() documentation.

AI-assistance disclosure: This article was drafted with AI assistance and should be reviewed for the application's rules.

from decimal import Decimal, ROUND_HALF_UP

amount = Decimal("12.345")
minor_unit = Decimal("0.01")
rounded = amount.quantize(minor_unit, rounding=ROUND_HALF_UP)

assert rounded == Decimal("12.35")
assert rounded.as_tuple().exponent == -2

print(f"rounded={rounded:.2f}")
rounded=12.35

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic