w3resource

Python Math: Round a specified decimal by setting precision

Python Math: Exercise-40 with Solution

Write a Python program to round a specified decimal by setting precision (between 1 and 4).

Sample Solution:

Python Code:

import decimal

d = decimal.Decimal('00.26598')
print("Original Number : ",d)
for i in range(1, 5):
    decimal.getcontext().prec = i
    print("Precision-",i, ':', d * 1)

Sample Output:

Original Number :  0.26598                                                                                    
Precision- 1 : 0.3                                                                                            
Precision- 2 : 0.27                                                                                           
Precision- 3 : 0.266                                                                                          
Precision- 4 : 0.2660

Pictorial Presentation:

Python Math: Round a specified decimal by setting precision

Flowchart:

Flowchart: Round a specified decimal by setting precision

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to retrieve the current global context (public properties) for all decimal.
Next: Write a Python program to round a specified number upwards towards infinity and down towards negative infinity of precision 4.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/math/python-math-exercise-40.php