The decimal
module provides support for fast correctly rounded decimal floating-point arithmetic. It offers several advantages over the float
datatype:
- Decimal is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school. – excerpt from the decimal arithmetic specification.
- Decimal numbers can be represented exactly. In contrast, numbers like
1.1
and2.2
do not have exact representations in binary floating point. End users typically would not expect1.1 + 2.2
to display as3.3000000000000003
as it does with binary floating point. - The exactness carries over into arithmetic. In decimal floating point,
0.1 + 0.1 + 0.1 - 0.3
is exactly equal to zero. In binary floating point, the result is5.5511151231257827e-017
. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.