New in version 2.4.
The decimal module provides support for decimal floating point arithmetic. It offers several advantages over the float() datatype:
>>> getcontext().prec = 6 >>> Decimal(1) / Decimal(7) Decimal("0.142857") >>> getcontext().prec = 28 >>> Decimal(1) / Decimal(7) Decimal("0.1428571428571428571428571429")
The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.
A decimal number is immutable. It has a sign, coefficient digits, and an exponent. To preserve significance, the coefficient digits do not truncate trailing zeroes. Decimals also include special values such as Infinity, -Infinity, and NaN. The standard also differentiates -0 from +0.
The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, and ROUND_UP.
Signals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, considered as informational, or treated as exceptions. The signals in the decimal module are: Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, and Underflow.
For each signal there is a flag and a trap enabler. When a signal is encountered, its flag incremented from zero and, then, if the trap enabler is set to one, an exception is raised. Flags are sticky, so the user needs to reset them before monitoring a calculation.
IBM's General Decimal Arithmetic Specification, The General Decimal Arithmetic Specification.
IEEE standard 854-1987, Unofficial IEEE 854 Text.