Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

decimal — decimal arithmetic

The decimal module provides Decimal for decimal calculations with explicit precision and rounding control, useful for monetary amounts and similar data.

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

Syntax

import decimal

decimal.Decimal('1.25')
with decimal.localcontext(prec=28):
    decimal.Decimal('1.255').quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_EVEN)

decimal is a standard-library module providing the Decimal type. Unlike binary float, it can represent finite decimal fractions exactly and preserve trailing zeros.

Construct values from text, such as decimal.Decimal('0.1'). Construction from float preserves its exact binary value, not necessarily the intended decimal value.

Context precision controls significant digits in results, not decimal places; it does not truncate string-constructor digits. Division may require rounding. localcontext() temporarily changes settings and restores the previous ones.

quantize(decimal.Decimal('0.01')) sets an exponent corresponding to two decimal places. ROUND_HALF_EVEN resolves ties toward an even final digit. If precision is insufficient, quantize() signals InvalidOperation.

Examples

import decimal

with decimal.localcontext(prec=28):
    total = decimal.Decimal('0.10') * 3
    rounded = decimal.Decimal('2.675').quantize(
        decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_EVEN
    )
    print(total)
    print(rounded)

Result

0.30
2.68

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