Skip to content

Python Decimal Precision

  • by

In Python, the decimal module provides support for arbitrary-precision decimal arithmetic. This module is useful when you need to perform precise calculations with a specified number of decimal places, avoiding issues that arise from floating-point inaccuracies.

To control the precision of decimal calculations in Python using the decimal module, you can follow the syntax below:

from decimal import Decimal, getcontext

# Set the desired precision (number of decimal places) for all Decimal operations
getcontext().prec = <precision_value>

Here’s a breakdown of the syntax:

1. Import the necessary modules:

from decimal import Decimal, getcontext

2. Set the precision using the getcontext().prec attribute. Replace <precision_value> with the number of decimal places you want to use in your calculations.

from decimal import Decimal, getcontext

getcontext().prec = 10

After setting the precision, all calculations using Decimal objects will be rounded to the specified number of decimal places. Keep in mind that setting a higher precision may require more memory and processing time, so use an appropriate precision value based on your specific needs.

Python Decimal Precision example

Here’s an example that demonstrates how to use the decimal module in Python to control the precision of calculations:

from decimal import Decimal, getcontext

# Set the desired precision (number of decimal places) for all Decimal operations
getcontext().prec = 5

# Example calculation with the specified precision
x = Decimal('1.23456789')
y = Decimal('2.34567891')

# Addition
result_add = x + y

# Division
result_div = x / y

# Multiplication
result_mul = x * y

print("x:", x)
print("y:", y)
print("Addition:", result_add)
print("Division:", result_div)
print("Multiplication:", result_mul)

Output:

Python Decimal Precision

In this example, we set the precision to 5 decimal places using getcontext().prec = 5. As a result, all calculations involving Decimal objects (x, y, and the results) will be rounded to 5 decimal places.

You can modify the getcontext().prec value to control the precision of the calculations based on your specific needs. The higher the precision, the more accurate the results, but keep in mind that higher precision may also require more computational resources. So, choose an appropriate precision depending on your use case.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *