Python Glossary Русский

all Python 3Numbers & mathterm

decimal.Decimal

decimal

Exact decimal arithmetic, free of float error. Indispensable in financial calculations.

Syntax

from decimal import Decimal
Decimal('1.1') + Decimal('2.2')

Build a Decimal from a string: Decimal(0.1) swallows the already-inexact binary float and prints it in full gory detail, while Decimal('0.1') is exactly one tenth. Arithmetic between Decimal and float is a TypeError (with int it is fine), and the default context keeps 28 significant digits, so a division like 10/3 still gets rounded — just predictably, in decimal.

Examples

from decimal import Decimal
Decimal('1.1') + Decimal('2.2') # → Decimal('3.3')
1.1 + 2.2 # → 3.3000000000000003
Decimal('10') / Decimal('3') # → Decimal('3.333...3')
Decimal('0.1') * 3 == Decimal('0.3') # → True
Decimal(1) / Decimal(7) # → Decimal('0.1428...')  (28 цифр)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy