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 - In this tutorial, you'll learn about the Python decimal module that supports fast correctly-rounded decimal floating-point 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
How do you get a decimal in python? - Stack Overflow
In a truly surreal experience, I have spent 20 minutes on a task I thought would take 20 seconds. I want to use decimals with 3 or more places. I cannot get anything over 1 place, and even in that... More on stackoverflow.com
🌐 stackoverflow.com
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 24, 2015
🌐
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
🌐
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 Β»
🌐
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 ...
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.

🌐
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')
Find elsewhere
🌐
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
🌐
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
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.
🌐
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.
🌐
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.
🌐
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
Decimal operators also accept integer arguments, but floating point values must be converted to Decimal instances. $ python decimal_operators.py a = 5.1 b = 3.14 c = 4 d = 3.14 a + b = 8.24 a - b = 1.96 a * b = 16.014 a / b = 1.624203821656050955414012739 a + c = 9.1 a - c = 1.1 a * c = 20.4 a / c = 1.275 a + d = unsupported operand type(s) for +: 'Decimal' and 'float'
🌐
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.
Top answer
1 of 5
22

In Python 2, 1/3 does integer division because both operands are integers. You need to do float division:

Copy1.0/3.0

Or:

Copyfrom __future__ import division

Which will make / do real division and // do integer division. This is the default as of Python 3.

2 of 5
7

If you divide 2 integers you'll end up with a truncated integer result (i.e., any fractional part of the result is discarded) which is why

Copy 1 / 3

gives you:

Copy 0

To avoid this problem, at least one of the operands needs to be a float. e.g., 1.0 / 3 or 1 / 3.0 or (of course) 1.0 / 3.0 will avoid integer truncation. This behavior is not unique to Python by the way.

(Edit: As mentioned in a helpful comment below by @Ivc if one of the integer operands is negative, the result is floor()'ed instead - see this article on the reason for this).

Also, there might be some confusion about the internal and external represenation of the number. The number is what it is, but we can determine how it's displayed.

You can control the external representation with formatting instructions. For instance a number can be displayed with 5 digits after the decimal point like this:

Copyn = 1/3.0

print '%.5f' %n
0.33333

To get 15 digits after the decimal.

Copyprint '%.15f' %n
0.333333333333333

Finally, there is a "new and improved" way of formatting strings/numbers using the .format() function which will be around for probably much longer than the %-formatting I showed above. An example would be:

Copyprint 'the number is {:.2}'.format(1.0/3.0)

would give you:

Copythe number is 0.33
🌐
LabEx
labex.io β€Ί tutorials β€Ί python-how-to-format-decimal-output-in-python-421895
How to format decimal output in Python | LabEx
Learn essential techniques for formatting decimal numbers in Python, including precision control, rounding, and display methods for professional data presentation.
🌐
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.