Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Decimal.quantize — setting a decimal exponent

decimal.Decimal.quantize uses the exponent of exp as the target and rounds the value if necessary. Use it to set a target number of decimal places and explicitly select a rounding rule. With clamp=1, a finite result can have a lower stored exponent.

Version: Python 3.14; repository image, production runtime not attested

Syntax

Decimal.quantize(exp, rounding=None, context=None)

decimal.Decimal.quantize returns a new Decimal. The exponent of exp sets the target scale: Decimal('0.01') targets two decimal places, not multiples of the value of exp. With clamp=1 in the context, the operation can lower the stored exponent of a finite result and append zeros to its coefficient without changing the result's numerical value.

The rounding argument overrides the rule in context; omitting both uses the current context. Construct values from strings to avoid importing float approximations.

Exceeding the context precision for the result's coefficient signals InvalidOperation: an enabled trap raises an exception; otherwise the result is NaN. Context exponent limits also apply. The operation never signals Underflow.

The example compares ROUND_HALF_EVEN with ROUND_HALF_UP and demonstrates adding trailing zeros.

Examples

from decimal import Context, Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP

ctx = Context(prec=10)
value = Decimal('2.665')
places = Decimal('0.01')

print(value.quantize(places, rounding=ROUND_HALF_EVEN, context=ctx))
print(value.quantize(places, rounding=ROUND_HALF_UP, context=ctx))
print(Decimal('2').quantize(places, context=ctx))

Result

2.66
2.67
2.00

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources