The python decimal module

Mary-Kate Olsen
Release: 2024-09-26 07:25:02
Original
1067 people have browsed it

El módulo decimal de python

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
Copy after login

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
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template