Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

decimal.Decimal — decimal numbers

decimal.Decimal represents decimal numbers and lets you control the precision and rounding of arithmetic.

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

Syntax

decimal.Decimal(value='0', context=None)

decimal.Decimal is an immutable decimal type. Its constructor accepts, among others, str, int, float, or Decimal; omitting the argument creates zero. Trailing zeros are preserved.

Use strings: Decimal('0.1') is exact, whereas Decimal(0.1) preserves the binary float approximation. Arithmetic mixing Decimal and float usually raises TypeError.

Context precision controls significant digits in results, not decimal places or constructor digits. quantize(Decimal('0.01')) sets two decimal places. The example isolates its context with localcontext; ROUND_HALF_EVEN resolves ties toward an even final digit.

Examples

from decimal import Context, Decimal, ROUND_HALF_EVEN, localcontext

with localcontext(Context(prec=28, rounding=ROUND_HALF_EVEN)):
    total = Decimal('0.10') + Decimal('0.20')
    rounded = Decimal('2.675').quantize(Decimal('0.01'))
    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