A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/floor-ceil-function-python/ below:

floor() and ceil() function Python

floor() and ceil() function Python

Last Updated : 08 Apr, 2025

Python provides a built-in math module that includes many useful mathematical functions and constants. It is commonly used for operations such as rounding numbers, working with trigonometric functions, performing logarithmic calculations, and more."

Among these are two commonly used functions:

These functions are part of the math module, so you need to import it before using them. Let's look at an example:

Python
import math

x = 3.7

print(math.floor(x))  
print(math.ceil(x))   

Explanation:

Syntax

math.floor(number)
math.ceil(number)

Parameters:

Return Type: Both functions return an integer value.

Examples of floor() and ceil() Example 1: Round a List of Floats Down and Up

Let’s take a list of floating-point numbers and apply both floor() and ceil() to each value.

Python
import math

a = [1.1, 2.5, 3.9, 4.0, 5.8]

fl = list(map(math.floor, a))
cl = list(map(math.ceil, a))

print("Floor:", fl)
print("Ceil :", cl)

Output
('Floor:', [1.0, 2.0, 3.0, 4.0, 5.0])
('Ceil :', [2.0, 3.0, 4.0, 4.0, 6.0])

Explanation:

Example 2: Compare floor() and ceil() with Negative Numbers Python
import math

a = -2.3
b = -5.9

print("floor(-2.3):", math.floor(a))
print("ceil(-2.3) :", math.ceil(a))

print("floor(-5.9):", math.floor(b))
print("ceil(-5.9) :", math.ceil(b))

Output
('floor(-2.3):', -3.0)
('ceil(-2.3) :', -2.0)
('floor(-5.9):', -6.0)
('ceil(-5.9) :', -5.0)

Explanation:

Example 3: Round User Input to Nearest Integer. Python
import math

a = float(input("Enter a number: "))

print("Rounded down using floor():", math.floor(a))
print("Rounded up using ceil():", math.ceil(a))

Suppose the user inputs 7.3, then the output will be:

Rounded down using floor(): 7
Rounded up using ceil(): 8
Computing Floor and Ceil Without Importing math

Apart from using the math module, we can also compute the floor and ceil of a float using basic arithmetic operations like floor division (//) and addition.

Concept:

Note: This method works well for positive numbers. For negative numbers, it may not give accurate ceiling values.

Example: Floor and Ceil using Integer Division Python
x = 4.5

f = x // 1
print(f)

c = x // 1 + 1
print(c)  

Explanation:


floor() and ceil() function Python


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4