The Decimal class is best for financial type addition, subtraction multiplication, division type problems:

>>> (1.1+2.2-3.3)*10000000000000000000
4440.892098500626                            # relevant for government invoices...
>>> import decimal
>>> D=decimal.Decimal
>>> (D('1.1')+D('2.2')-D('3.3'))*10000000000000000000
Decimal('0.0')

The Fraction module works well with the rational number problem domain you describe:

>>> from fractions import Fraction
>>> f = Fraction(1) / Fraction(3)
>>> f
Fraction(1, 3)
>>> f * 3 < 1
False
>>> f * 3 == 1
True

For pure multi precision floating point for scientific work, consider mpmath.

If your problem can be held to the symbolic realm, consider sympy. Here is how you would handle the 1/3 issue:

>>> sympy.sympify('1/3')*3
1
>>> (sympy.sympify('1/3')*3) == 1
True

Sympy uses mpmath for arbitrary precision floating point, includes the ability to handle rational numbers and irrational numbers symbolically.

Consider the pure floating point representation of the irrational value of โˆš2:

>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(2)*math.sqrt(2)
2.0000000000000004
>>> math.sqrt(2)*math.sqrt(2)==2
False

Compare to sympy:

>>> sympy.sqrt(2)
sqrt(2)                              # treated symbolically
>>> sympy.sqrt(2)*sympy.sqrt(2)==2
True

You can also reduce values:

>>> import sympy
>>> sympy.sqrt(8)
2*sqrt(2)                            # โˆš8 == โˆš(4 x 2) == 2*โˆš2...

However, you can see issues with Sympy similar to straight floating point if not careful:

>>> 1.1+2.2-3.3
4.440892098500626e-16
>>> sympy.sympify('1.1+2.2-3.3')
4.44089209850063e-16                   # :-(

This is better done with Decimal:

>>> D('1.1')+D('2.2')-D('3.3')
Decimal('0.0')

Or using Fractions or Sympy and keeping values such as 1.1 as ratios:

>>> sympy.sympify('11/10+22/10-33/10')==0
True
>>> Fraction('1.1')+Fraction('2.2')-Fraction('3.3')==0
True

Or use Rational in sympy:

>>> frac=sympy.Rational
>>> frac('1.1')+frac('2.2')-frac('3.3')==0
True
>>> frac('1/3')*3
1

You can play with sympy live.

Answer from dawg on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ decimal.html
decimal โ€” Decimal fixed-point and floating-point arithmetic
Note Decimal.from_float(0.1) is ...51231257827021181583404541015625. ... From Python 3.2 onwards, a Decimal instance can also be constructed directly from a float....
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ advanced python โ€บ python decimal
An Essential Guide to Python Decimal By Examples
February 26, 2021 - Unlike floats, Python represents decimal numbers exactly. And the exactness carries over into arithmetic.
Discussions

Clarification on the Decimal type in Python - Stack Overflow
Everybody knows, or at least, every programmer should know, that using the float type could lead to precision errors. However, in some cases, an exact solution would be great and there are cases wh... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What's different between Decimal and Floating point numbers in Python?
Python's integers (ยฑ0, 1, 2, etc.) have unlimited accuracy, which is unusual as far as programming languages go. In most languages they usually cap at 64-bits (aka long int) and there may be multiple integer types of various sizes. This makes Python very useful for scientific computing as you don't need a separate BigNum library to handle arbitrary precision. Python's floating-point numbers don't quite have this same luxury due to the inaccurate nature of them. Since many decimal numbers cannot be accurately represented in binary, floating-point math will always run into inaccuracies. For instance, 0.1 + 0.1 + 0.1 isn't 0.3, but something like 0.3000000000001. You'll use floats whenever whole numbers aren't enough, but you don't need a specific amount of accuracy. You probably never meant to ask about this, but decimal.Decimal is an alternative to float that lets you set its precision yourself. It's still not infinitely accurate, but it's often used in scientific computing where integers just can't cut it. More on reddit.com
๐ŸŒ r/learnpython
6
5
March 5, 2021
Question about decimal accuracy

That is not a Decimal type, it's an int.

>>> import math
>>> n = math.factorial(10000)
>>> type(n)
<class 'int'>

Since the maximum integer that can be stored on a 64 bit architecture it's about 20 digits of length

That is true from a hardware perspective, and many programming languages copy that truth into the language, but it's not true in python. A python int can be any size, and has perfect precision.

More on reddit.com
๐ŸŒ r/Python
5
0
November 23, 2015
How do I represent currency (i.e., rounding to two decimal places) in Python? I just started learning a few days ago, and any explanation I've found of the decimal function is overwhelming at this point. ELI5, plz?

You're thinking about the wrong aspect of the problem. Yes, floating point innaccuracies mean you get a number like 30.00000000000000001, and decimal will fix that - but you can still divide a price and get a value like $3.718. Decimal won't help you there.

What you really want is a way to round the value to 2 decimal places when you print it. That's the only time that it matters, unless you're a bank and you really care about tiny fractions of a cent (in which case you'll use decimal as well as the following advice).

Check out the format function.

price=14.6188
print("The price is: ${:.2f}".format(price))
The price is: $14.62

This function is very powerful and you should get familiar with it.

product="beer"
print("The price of {:} is ${:.2f}".format(product, price))
The price of beer is $14.62
More on reddit.com
๐ŸŒ r/learnpython
19
12
September 14, 2012
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ decimal
decimal | Python Standard Library โ€“ Real Python
>>> from decimal import Decimal >>> Decimal("0.1") + Decimal("0.2") Decimal('0.3') >>> # Using the built-in float >>> 0.1 + 0.2 0.30000000000000004
๐ŸŒ
Python
peps.python.org โ€บ pep-0327
PEP 327 โ€“ Decimal Data Type - Python Enhancement Proposals
Decimal will be floating point (as opposed to fixed point) and will have bounded precision (the precision is the upper limit on the number of significant digits in a result). However, precision is user-settable, and a notion of significant trailing ...
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ decimal
Python Decimal - high-precision calculations in Python with Decimal
January 29, 2024 - It is possible to change the default precision of the Decimal type. In the following example, we also use the mpmath module, which is a library for arbitrary-precision floating-point arithmetic. ... We need to install mpmath first. ... #!/usr/bin/python from decimal import Decimal, getcontext import math import mpmath getcontext().prec = 50 mpmath.mp.dps = 50 num = Decimal(1) / Decimal(7) num2 = mpmath.mpf(1) / mpmath.mpf(7) print(" math.sqrt: {0}".format(Decimal(math.sqrt(num)))) print("decimal.sqrt: {0}".format(num.sqrt())) print(" mpmath.sqrt: {0}".format(mpmath.sqrt(num2))) print('actual value: 0.3779644730092272272145165362341800608157513118689214')
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_module_decimal.asp
Python decimal Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... from decimal import Decimal print(Decimal('0.1') + Decimal('0.2')) print(Decimal('1') / Decimal('4')) Try it Yourself ยป
Find elsewhere
Top answer
1 of 5
63

The Decimal class is best for financial type addition, subtraction multiplication, division type problems:

>>> (1.1+2.2-3.3)*10000000000000000000
4440.892098500626                            # relevant for government invoices...
>>> import decimal
>>> D=decimal.Decimal
>>> (D('1.1')+D('2.2')-D('3.3'))*10000000000000000000
Decimal('0.0')

The Fraction module works well with the rational number problem domain you describe:

>>> from fractions import Fraction
>>> f = Fraction(1) / Fraction(3)
>>> f
Fraction(1, 3)
>>> f * 3 < 1
False
>>> f * 3 == 1
True

For pure multi precision floating point for scientific work, consider mpmath.

If your problem can be held to the symbolic realm, consider sympy. Here is how you would handle the 1/3 issue:

>>> sympy.sympify('1/3')*3
1
>>> (sympy.sympify('1/3')*3) == 1
True

Sympy uses mpmath for arbitrary precision floating point, includes the ability to handle rational numbers and irrational numbers symbolically.

Consider the pure floating point representation of the irrational value of โˆš2:

>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(2)*math.sqrt(2)
2.0000000000000004
>>> math.sqrt(2)*math.sqrt(2)==2
False

Compare to sympy:

>>> sympy.sqrt(2)
sqrt(2)                              # treated symbolically
>>> sympy.sqrt(2)*sympy.sqrt(2)==2
True

You can also reduce values:

>>> import sympy
>>> sympy.sqrt(8)
2*sqrt(2)                            # โˆš8 == โˆš(4 x 2) == 2*โˆš2...

However, you can see issues with Sympy similar to straight floating point if not careful:

>>> 1.1+2.2-3.3
4.440892098500626e-16
>>> sympy.sympify('1.1+2.2-3.3')
4.44089209850063e-16                   # :-(

This is better done with Decimal:

>>> D('1.1')+D('2.2')-D('3.3')
Decimal('0.0')

Or using Fractions or Sympy and keeping values such as 1.1 as ratios:

>>> sympy.sympify('11/10+22/10-33/10')==0
True
>>> Fraction('1.1')+Fraction('2.2')-Fraction('3.3')==0
True

Or use Rational in sympy:

>>> frac=sympy.Rational
>>> frac('1.1')+frac('2.2')-frac('3.3')==0
True
>>> frac('1/3')*3
1

You can play with sympy live.

2 of 5
6

So, my question is: is there a way to have a Decimal type with an infinite precision?

No, since storing an irrational number would require infinite memory.

Where Decimal is useful is representing things like monetary amounts, where the values need to be exact and the precision is known a priori.

From the question, it is not entirely clear that Decimal is more appropriate for your use case than float.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ decimal-functions-python-set-1
Decimal Functions in Python | Set 1 - GeeksforGeeks
Returns 1 if 1st Decimal argument is greater than 2nd(ignoring sign), -1 if 1st Decimal argument is smaller than 2nd(ignoring sign) and 0 if both are equal(ignoring sign). ... # Python code to demonstrate the working of # compare() and compare_total_mag() # importing "decimal" module to use decimal functions import decimal # Initializing decimal number a = decimal.Decimal(9.53) # Initializing decimal number b = decimal.Decimal(-9.56) # comparing decimal numbers using compare() print ("The result of comparison using compare() is : ",end="") print (a.compare(b)) # comparing decimal numbers using compare_total_mag() print ("The result of comparison using compare_total_mag() is : ",end="") print (a.compare_total_mag(b))
Published ย  January 7, 2025
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ python decimal module
Python Decimal Module | Scaler Topics
May 4, 2023 - There are several different numeric data types in Python, including int, float, and complex numbers, but due to floating point numbers' machine-dependent nature, we need a more precise data type. This article examines the Python decimal module, which implements decimal numbers with precision of up to 28 digits.
Top answer
1 of 4
9
Integers (int type) are "whole numbers", without the fractional part, eg. 10. You use this type when the value is always an integer, e.g. a counter. Floating point numbers (float type) can have fractional part, e.g. 10.1234. They are stored using the closest representation in binary notation. Most numbers cannot be represented accurately, so they are slightly off. You use float for most mathematical calculations involving fractional numbers. Decimal numbers (Decimal type in Python) are used to represent floating point numbers accurately, with a defined precision (a defined number of places after decimal point). They are represented with two integer numbers, one for the integer part and one for the fractional part. For example. 10.1234 is stored as (10, 1234). Decimal type is required when fractional numbers must be represented accurately, with defined precision. The most notable example is financial calculations. Using float type you may get a result of a financial operation as 1010.123456$. But money is expressed with at most two decimal places. What does 0.123456$ mean? You can round it to 1010.12$, but then what happens with the remaining 0.003456$? Some "smart" programmers used that to their advantage in the past and they made a lot of money (which they eventually had to give back). So, for money calculations, you should use Decimal type. A good explanation of the Decimal type is in the documentation: https://docs.python.org/3/library/decimal.html
2 of 4
7
Python's integers (ยฑ0, 1, 2, etc.) have unlimited accuracy, which is unusual as far as programming languages go. In most languages they usually cap at 64-bits (aka long int) and there may be multiple integer types of various sizes. This makes Python very useful for scientific computing as you don't need a separate BigNum library to handle arbitrary precision. Python's floating-point numbers don't quite have this same luxury due to the inaccurate nature of them. Since many decimal numbers cannot be accurately represented in binary, floating-point math will always run into inaccuracies. For instance, 0.1 + 0.1 + 0.1 isn't 0.3, but something like 0.3000000000001. You'll use floats whenever whole numbers aren't enough, but you don't need a specific amount of accuracy. You probably never meant to ask about this, but decimal.Decimal is an alternative to float that lets you set its precision yourself. It's still not infinitely accurate, but it's often used in scientific computing where integers just can't cut it.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ decimal-functions-in-python
Decimal Functions in Python
July 30, 2019 - In Python, there is a module called Decimal, which is used to do some decimal floating point related tasks. This module provides correctly-rounded floating point arithmetic. To use it at first we need to import it the Decimal standard libra
๐ŸŒ
Readthedocs
pydoc-zh.readthedocs.io โ€บ en โ€บ latest โ€บ library โ€บ decimal.html
9.4. decimal โ€” Decimal fixed point and floating point arithmetic โ€” Python 2.7.6 documentation
Note Decimal.from_float(0.1) is ... 0.1000000000000000055511151231257827021181583404541015625. ... From Python 2.7 onwards, a Decimal instance can also be constructed directly from a float....
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ decimal module in python
Decimal Module in Python - PythonForBeginners.com
June 24, 2021 - Python has numeric data types like int, float and complex numbers but due to the machine dependent nature of floating point numbers, we need a more precise data type for calculations which demand high precision. In this article, we will study about the decimal module in python which implements the decimal numbers having precision of upto 28 digits.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ decimal
decimal โ€“ Fixed and floating point math - Python Module of the Week
import decimal # Set up a context with limited precision c = decimal.getcontext().copy() c.prec = 3 # Create our constant pi = c.create_decimal('3.1415') # The constant value is rounded off print 'PI:', pi # The result of using the constant uses the global context print 'RESULT:', decimal.Decimal('2.01') * pi ยท $ python decimal_instance_context.py PI: 3.14 RESULT: 6.3114
๐ŸŒ
Medium
medium.com โ€บ @hadi1812001 โ€บ decimal-class-in-python-an-intro-and-its-use-cases-28dc84380d87
Decimal Class in Python: An Intro and its Use Cases | by Hadi | Medium
February 8, 2023 - The Decimal class in Python is part of the decimal module, and it provides support for fast correctly rounded decimal floating pointโ€ฆ
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ rounding-to-two-decimal-places-in-pythonn
Rounding to Two Decimal Places in Python | Codecademy
Learn how to round a number in Python to two decimal places using the round, string formatting, and modulus operators.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ precision-handling-python
Precision Handling in Python - GeeksforGeeks
December 19, 2025 - Given a number, the task is to control its precision either by rounding it or formatting it to a specific number of decimal places. For Example: Input: x = 2.4 Output: Integral value = 2 Smallest integer greater than x = 3 Greatest integer smaller than x = 2 ยท Let's explore different ways to do this task in Python.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ python decimal module โ€“ 7 functions you need to know!
Python decimal module - 7 functions you need to know! - AskPython
August 6, 2022 - Value 1: -122.2000000000000028421709430404007434844970703125 Absolute value of the given decimal number: 122.2000000000000028421709430404007434844970703125 ยท The Python decimal module contains the following functions to calculate the minimum and maximum values of the decimal point numbers.