Home >Backend Development >Python Tutorial >The python decimal module
Programming languages have various types of data to handle numerical information. The integer (int), real (float) type and python supports others such as fractions and complexes.
Today, however, I want to talk about the decimal type. The float or floating point has several precision problems that cannot be tolerated in certain types of applications such as, for example, those that have to do with finance.
Let's look at a very simple case:
from decimal import Decimal 1.0 == 0.999999999999999999 # True Decimal("1.0") == Decimal("0.999999999999999999") # False
Extending on the decimal class, there is the py-money module that adds a currency such as USD or COP to the numbers, allowing applications that require it to have as high a precision as desired.
Of course it is not possible to have infinite precision on a computer. However, the decimal modulus can be set to as high a precision as needed:
print(getcontext().prec) # outpus 28 by default
I used the decimal module quite a bit and also the py-money library at a time when I was working on a financial application. It is correctly supported by django and other frameworks.
The above is the detailed content of The python decimal module. For more information, please follow other related articles on the PHP Chinese website!