- Published on
Use decimal for money
- Authors
- Name
- Lif
Problem
Float type comes with some precision issues.
>>> .1 + .1 + .1 == .3
False
>>> .1 + .1 + .1
0.30000000000000004
Because of the float approximation, the equation is not equal to 3.
Solution
If precision matters, use demical instead of float.
>>> from decimal import Decimal
>>> Decimal(".1") + Decimal(".1") + Decimal(".1") == Decimal(".3")
True
>>> Decimal(".1") + Decimal(".1") + Decimal(".1")
0.3