Python floor() and ceil() Functions

This is a detailed tutorial of Python floor() and ceil() functions. Learn to find the floor and ceiling value of any numerical value by using the math module.

Use of floor() and ceil() Functions

The math module comes pre-installed with Python. This module includes two object-type functions, math.floor() and math.ceil(). Both of these functions take a numerical value as an argument.

  • The floor() function will return the mathematical floor value of that numerical value passed as an argument i.e. the largest integer value which is not greater than the numerical value passed.
  • The ceil() function will return the mathematical ceiling value i.e. smallest integer value that is not less than the passed numerical value.

Find more about floor and ceiling values here.

Syntax

You must include the math module first in your program and then you can use the floor() and ceil() functions anywhere as the object-specific function of the math module.

import math
math.floor(x)
math.ceil(x)

In the above syntax, x is any numeric value or expression.

Examples

The following two examples illustrate the use of floor() and ceil() functions respectively.

Example 1.

The following code calculates the floor value of three different numerical values.

import math
num1 = 0.5
num2 = 3.5
num3 = -67.32
num1_floor = math.floor(num1)
num2_floor = math.floor(num2)
num3_floor = math.floor(num3)
print(num1_floor)
print(num2_floor)
print(num3_floor)

Python Floor() Function Example

Example 2.

The code given below calculates the ceiling value of three different numerical values which are the same as the numerical values used in the above example.

import math
num1 = 0.5
num2 = 3.5
num3 = -67.32
num1_ceil = math.ceil(num1)
num2_ceil = math.ceil(num2)
num3_ceil = math.ceil(num3)
print(num1_ceil)
print(num2_ceil)
print(num3_ceil)

Ceil() Function Example Python

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *