Skip to content
Related Articles
Open in App
Not now

Related Articles

Setting Precision in Python Using Decimal Module

Improve Article
Save Article
Like Article
  • Last Updated : 01 Oct, 2020
Improve Article
Save Article
Like Article

The decimal module in Python can be used to set the precise value of a number. The default value of the Decimal module is up to 28 significant figures. However, it can be changed using getcontext().prec method.

The below program demonstrates the use of decimal module by computing the square root of 2 numbers up to the default the number of places.

Python3




# Import required modules
import decimal  
  
# Create decimal object
ob1 = decimal.Decimal(5).sqrt()  
ob2 = decimal.Decimal(7).sqrt()
  
# Display value  
print(ob1)
print(ob2)

Output

2.236067977499789696409173669
2.645751311064590590501615754

We can set the precision up to n significant figure. The decimal.getcontext().prec has to be declared in the global scope such that all the decimal objects can have n significant figures.

Python3




# Import required module
import decimal
  
# Set precision to a fixed value 
decimal.getcontext().prec = 6  
  
# Create Decimal object
ob1 = decimal.Decimal(5).sqrt()  
ob2 = decimal.Decimal(7).sqrt()
  
# Display value up to 6 significant figures
print(ob1)
print(ob2)

Output

2.23607
2.64575

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!