Skip to content

floor and ceil in Python

  • by

In Python, the floor and ceil functions are part of the math module, which provides various mathematical operations. These functions help you round numbers down or up, respectively. To use them, you need to import the math module first.

Here’s the correct syntax for floor and ceil in Python:

import math

# The floor function rounds down to the nearest integer
x = 4.8
floor_x = math.floor(x)
print(floor_x)  # Output: 4

# The ceil function rounds up to the nearest integer
y = 2.3
ceil_y = math.ceil(y)
print(ceil_y)  # Output: 3
  1. floor: The floor function is used to round down a number to the nearest integer that is less than or equal to the input value. In other words, it removes the decimal part of a floating-point number and returns the largest integer not greater than the input.
  2. ceil: The ceil function is used to round up a number to the nearest integer that is greater than or equal to the input value. It effectively rounds the number to the smallest integer not less than the input.

floor and ceil in Python example

Here’s a comprehensive example demonstrating the usage of math.floor() and math.ceil() in Python:

import math

# math.floor()
number1 = 7.8
floor_number1 = math.floor(number1)
print(f"Floor of {number1} is: {floor_number1}")

# Using math.ceil()
number2 = 3.2
ceil_number2 = math.ceil(number2)
print(f"Ceil of {number2} is: {ceil_number2}")

# Using math.floor() and math.ceil() with negative numbers
number3 = -6.5

floor_number3 = math.floor(number3)
ceil_number3 = math.ceil(number3)
print(f"Floor of {number3} is: {floor_number3}")
print(f"Ceil of {number3} is: {ceil_number3}")   

Output:

floor and ceil in Python

In this example, we use math.floor() to round down the numbers to the nearest integer and math.ceil() to round up to the nearest integer. Note that math.floor() always returns the largest integer less than or equal to the input, and math.ceil() returns the smallest integer greater than or equal to the input.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading