Python: Configure the rounding to round to the nearest - with ties going towards 0, with ties going away from 0
5. Rounding with Tie-Breaking Rules
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:

For more Practice: Solve these Related Problems:
- Write a Python program to round a Decimal value using both ROUND_HALF_DOWN and ROUND_HALF_UP modes, and then print the two results side by side.
- Write a Python function that takes a Decimal and applies tie-breaking rounding (half down and half up) to show the difference when the value is exactly halfway between two multiples.
- Write a Python script to generate a list of Decimal values with midpoints and round them using both ROUND_HALF_DOWN and ROUND_HALF_UP, then output the results in a comparison table.
- Write a Python program to demonstrate the effect of tie-breaking rules on Decimal values by rounding a series of midpoints using both rounding modes.
Go to:
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.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.