The floor and ceiling functions are used most frequently in maths or computer programming. These functions return the nearest integer value of a fractional number.
Today in this article I will discuss the usage of the floor() and ceil() functions in Python programming.
Python floor() method
Both Python floor() and ceil() methods are the parts of the math library in Python. Python floor() method accepts a fractional number and returns greatest integer which is smaller than number itself.
For example if you pass 10.5 as input to the floor() method it will return 10 as output.
The syntax of Python floor() method
import math math.floor(x)
You need to import math library in order to use Python floor() and ceil() methods.
Example:
The following program shows the usage of floor method in Python.
import math
x,y,z = 5 , -15.3 , 19.7
print(math.floor(x))
print(math.floor(y))
print(math.floor(z))
Now save this code with .py extension on your system and use the given command to run it.
python3 floor.py
This will display the output as you can see in the image below.
Python ceil() method
Python ceil() method accepts a fractional number and returns the smallest integer which is greater than number itself.
For example if you pass 10.5 as input to the ceil() method it will return 11 as output.
The syntax of Python ceil() method
import math math.ceil(x)
Again you need to import math library in order to use Python ceil() method.
Example:
The following program shows the usage of ceil() method in Python.
import math
x,y,z = 5 , -15.3 , 19.7
print(math.ceil(x))
print(math.ceil(y))
print(math.ceil(z))
Save this code with the .py extension on your system and use the following command to execute –
python3 ceil.py
This will display the output as you can see in the image below.
Conclusion
So here you have learnt how to use Python floor() and ceil() methods. Now if you have a query or feedback then write us in the comments below.