How to Use Python decimal Module

09/12/2021

Contents

In this article, you will learn how to use Python decimal module.

Python decimal Module

The decimal module in Python provides a way to perform accurate decimal arithmetic. It is particularly useful for financial and monetary calculations, where precision is important.

Here are the steps to use the decimal module in Python:

Import the decimal module:
import decimal
Set the precision of the decimal module:

The precision determines the number of significant digits that will be used for calculations. You can set the precision to a specific value using the getcontext() method.

decimal.getcontext().prec = 10

This will set the precision to 10 significant digits.

Create a Decimal object:

You can create a Decimal object by passing a string or a number to the Decimal() constructor.

x = decimal.Decimal('10.25')
y = decimal.Decimal(5)

This creates a Decimal object with the value 10.25 and another Decimal object with the value 5.

Perform arithmetic operations:

You can perform arithmetic operations such as addition, subtraction, multiplication, and division on Decimal objects just like regular numbers.

z = x + y

This will add the two Decimal objects x and y together and store the result in a new Decimal object z.

Convert the Decimal object to a float or an int:

If you want to convert a Decimal object to a float or an int, you can use the float() or int() method.

float_z = float(z)
int_z = int(z)

These will convert the Decimal object z to a float and an int, respectively.

Here’s an example of how you can use the decimal module to perform arithmetic operations with a high degree of accuracy:

import decimal

# Set the precision to 10 significant digits
decimal.getcontext().prec = 10

# Create Decimal objects
x = decimal.Decimal('10.25')
y = decimal.Decimal(5)

# Perform arithmetic operations
z = x + y
w = x * y

# Convert Decimal objects to float and int
float_z = float(z)
int_w = int(w)

print(z)        # Output: 15.25
print(w)        # Output: 51.25
print(float_z)  # Output: 15.25
print(int_w)    # Output: 51