Python: Configure the rounding to round to the nearest - with ties going towards 0, with ties going away from 0
Python module: Exercise-5 with Solution
Write a Python program that can be configured to round to the nearest - with ties going towards 0 and ties going away from 0. Use decimal.ROUND_HALF_DOWN, decimal.ROUND_HALF_UP
Sample Solution:
Python Code:
import decimal
print("Configure the rounding to round to the nearest, with ties going towards 0:")
decimal.getcontext().prec = 1
decimal.getcontext().rounding = decimal.ROUND_HALF_DOWN
print(decimal.Decimal(10) / decimal.Decimal(4))
print("\nConfigure the rounding to round to the nearest, with ties going away from 0:")
decimal.getcontext().prec = 1
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
print(decimal.Decimal(10) / decimal.Decimal(4))
Sample Output:
Configure the rounding to round to the nearest, with ties going towards 0: 2 Configure the rounding to round to the nearest, with ties going away from 0: 3
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to configure the rounding to round to the floor, ceiling.
Next: Write a Python program to configure the rounding to round to the nearest, with ties going to the nearest even integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://198.211.115.131/python-exercises/modules/python-module-decimal-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics