floor() and ceil() function Python

Python's math module provides two useful functions for rounding decimal numbers to integers: floor() and ceil(). These functions help convert fractional numbers to their nearest integer values in different directions.

floor() Function

The floor() function returns the largest integer that is less than or equal to the given number. For positive numbers, it rounds down; for negative numbers, it rounds away from zero.

Syntax

math.floor(x)
Where x is a numeric value

Example of floor()

Let's see how floor() works with different types of numeric values ?

import math

x, y, z = 21, -23.6, 14.2
print("The value of", x, "on applying floor() function is:", math.floor(x))
print("The value of", y, "on applying floor() function is:", math.floor(y))
print("The value of", z, "on applying floor() function is:", math.floor(z))

The output of the above code is ?

The value of 21 on applying floor() function is: 21
The value of -23.6 on applying floor() function is: -24
The value of 14.2 on applying floor() function is: 14

ceil() Function

The ceil() function returns the smallest integer that is greater than or equal to the given number. For positive numbers, it rounds up; for negative numbers, it rounds toward zero.

Syntax

math.ceil(x)
Where x is a numeric value

Example of ceil()

Here's how ceil() behaves with various numeric values ?

import math

x, y, z = 21, -23.6, 14.2
print("The value of", x, "on applying ceil() function is:", math.ceil(x))
print("The value of", y, "on applying ceil() function is:", math.ceil(y))
print("The value of", z, "on applying ceil() function is:", math.ceil(z))

The output of the above code is ?

The value of 21 on applying ceil() function is: 21
The value of -23.6 on applying ceil() function is: -23
The value of 14.2 on applying ceil() function is: 15

Comparison

Function Direction Example Result
floor() Rounds down (toward negative infinity) floor(3.7) 3
ceil() Rounds up (toward positive infinity) ceil(3.2) 4
floor() For negative numbers floor(-2.3) -3
ceil() For negative numbers ceil(-2.7) -2

Conclusion

Use math.floor() to round down to the nearest integer and math.ceil() to round up. Both functions handle negative numbers by following their respective rounding directions toward negative or positive infinity.

Updated on: 2026-03-15T19:08:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements