Python Glossary Русский

all Python 3Numbers & mathterm

decimal

module

Decimal arithmetic with configurable precision and rounding rules: money and anything where 0.1 + 0.2 must be exactly 0.3.

Syntax

from decimal import Decimal

Use decimal where decimal precision and explicit rounding matter: sums of money, taxes, reports. float is faster but stores a binary fraction and gives 0.30000000000000004; for exact common fractions such as 1/3 there is fractions. The usual mistake is building a Decimal from a float: Decimal(0.1) carries the error along, so the value is passed as a string, Decimal('0.1').

Examples

from decimal import Decimal
print(0.1 + 0.2)  # → 0.30000000000000004
print(Decimal('0.1') + Decimal('0.2'))  # → 0.3
print(Decimal(0.1) == Decimal('0.1'))  # → False — из float приходит его двоичная погрешность

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy