w3resource

Python: Configure the rounding to round to the floor, ceiling


4. Floor and Ceiling Rounding

Write a Python program to configure the rounding to round to the floor, ceiling. Use decimal.ROUND_FLOOR, decimal.ROUND_CEILING

Sample Solution:

Python Code:

import decimal
print("Configure the rounding to round to the floor:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_FLOOR
print(decimal.Decimal(20) / decimal.Decimal(6))
print("\nConfigure the rounding to round to the ceiling:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_CEILING
print(decimal.Decimal(20) / decimal.Decimal(6))

Sample Output:

Configure the rounding to round to the floor:
3.333

Configure the rounding to round to the ceiling:
3.334

Flowchart:

Flowchart: Configure the rounding to round to the floor, ceiling.

For more Practice: Solve these Related Problems:

  • Write a Python program to round a Decimal value to the floor and ceiling using decimal.ROUND_FLOOR and decimal.ROUND_CEILING, and then print both rounded values.
  • Write a Python function that takes a Decimal value and returns a tuple with its floor and ceiling rounded results, then test it with various inputs.
  • Write a Python script to demonstrate the differences between floor and ceiling rounding on a list of Decimal values.
  • Write a Python program to configure a Decimal context for floor rounding, round several values, then reconfigure for ceiling rounding and print the outputs for comparison.

Python Code Editor:

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

Previous: Write a Python program to round a Decimal value to the nearest multiple of 0.10, unless already an exact multiple of 0.05.
Next: Write a Python program to configure the rounding to round to the nearest - with ties going towards 0, with ties going away from 0.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.