Python floor function

The Python floor() function is a math library method that returns the largest integer value that is less than or equal to the specified expression or value. In short, the floor() function rounds down the given number to the nearest integer.

The following visual representation shows the Python floor() function in action. The arrow pointer shows how the floor() function moves downwards for positive and negative values.

-∞….-3-2-10123….
<————- <————-

For a positive number, the floor() function returns the closest previous number towards 0 because it is less than or equal to the given number. For example, 1 < 2 < 3 <… ∞.

For a negative number, the Python floor() function returns the closest previous number towards -∞ because it is less than or equal to the given number. For example, (-∞ < …. < -3 < -2 < -1 < 0.

Python floor function syntax

The standard syntax of the math floor function after importing the math module is

import math

math.floor(number);

The above syntax calls the floor() function present in the math module. However, instead of importing the math module, if we import the floor() function, the syntax does not need math.

from math import floor

floor(number);

As you can see from the above syntax, the Python floor() function accepts numerical values (floating-point numbers). The floor() method returns the largest integer value less than or equal to a given number as output.

  • If the number argument is a positive or negative number, it returns the floor value.
  • If it is not a number, the math.floor() method returns TypeError.
  • If the given number is not a finite (inf) or not a number (NaN), the floor() function returns a ValueError.

Python floor function examples

The floor Function returns the largest integer value that is less than or equal to the given numeric value. The following series of examples shows how to use the math floor function.

floor() function on Positive Numbers

In the following example, we use the Python floor function on positive floating-point numbers. As we all know, the floor() function returns the greatest integer that is less than or equal to a user-specified number.

First, we imported the math library using the following statement. This will utilize mathematical functions like floor.

import math

Here, the floor value of both 5.2 and 5.9 returns 5 because the floor function does not follow the 5 rule and finds no difference in .2 and .9. Similarly, the flooring value of 0.9878 returns 0 because the floor() method ignores the decimals and moves closer to 0.

import math

a = 5.2
print(math.floor(a))
b = 5.9
print(math.floor(b))
c = 0.9878
print(math.floor(c))

Result

5
5
0

Python floor() function on Negative numbers

Most people are confused by the result of the floor function when we pass negative numbers as arguments. As we mentioned in the introduction, the floor() function moves towards negative infinity for negative numbers.

In the following example, we declared two variables with negative numbers: -90.98 and -0.78

  • -90.98: Here, -91 is the closest integer value that is less than -90.98.
  • -0.78: -1 is the largest integer number that is less than or equal to -0.78.
import math

a = -90.98
print(math.floor(a))
b = -0.78
print(math.floor(b))

Result

-91
-1

Python math floor function for positive and negative numbers

In this example, the floor() function accepts an argument and returns the smallest integer value of both positive and negative values. We have used an image to display the output of the positive and negative floor values.

TIP: Please refer to the remaining math functions articles in Python to understand the other calculations.

import math
 
print('The final result of math.floor(10.45) = ', math.floor(10.45))
print('The final result of math.floor(20.99) = ', math.floor(20.99))
print()

print('The final result of math.floor(-120.49) = ', math.floor(-120.49))
print('The final result of math.floor(-160.99) = ', math.floor(-160.99))
Python math floor Function Example

What is the floor value of 0 and integers?

As we all know, the Python floor() function returns the largest integer value less than or equal to the given number. Here, 25 <= 25 is True, so it returns 25. In other words, the largest number less than or equal to 25 is 25.

import math
n = 50
print(math.floor(n))
50

When you pass 0 to the math floor() function, it will return 0 as output. Let me pass 0 as the floor() argument to see the result.

import math
n = 0
print(math.floor(n))
0

Use the Python floor() function on user inputs

The following program allows the user to enter the floating-point numbers as input. Next, it uses the math floor() function on user given number to view the result. Here, we will use both positive and negative floating-point numbers as user inputs of the floor() function.

import math

a = float(input("Enter any Number: "))
print(math.floor(a))

Result

Enter any Number: 17.89
17
Enter any Number: -121.567
-122

Python floor function on math calculations

Apart from static variables or single numeric values, we can apply the floor() function on expressions to perform mathematical operations and round them.

In the example below, the first expression (2.45 + 7.55 – 14.88) performs addition and subtraction. Next, the floor() function is applied to the result.

a = math.floor(2.45 + 7.55 - 14.88)

It means

floor (2.45 + 7.55 – 14.88)

floor (-4.88) = – 5

The second one finds the floor value of the pi value.

Pi value = 3.1415 and its floor value should be 3.

import math 
a = math.floor(2.45 + 7.55 - 14.88)
b = math.floor(math.pi)
print(a)
print(b)
-5
3

Use the floor() function on a Boolean value

In the example below, we use the Python math.floor() function on a Boolean value, True and False. When you call the floor() function with True, the method considers it as 1, and finds the floor value of 1, which is 1. For False input, the result is 0.

import math
print(math.floor(True))
1

Python floor() function on aggregations

When working with financial reporting, data analysis, and so on, we always perform data aggregations. First, we use the available aggregate functions to find the sum, mean, median, etc of the existing data. Next, use the math floor() function to round the result.

In the following example, we used the sum() function to find the total project expenses by adding all items.

import math
projectExpenses = [1000.78, 300.67, 450.97, 980.7]

total = sum(projectExpenses)
print(math.floor(total))

The total project expenses are 2733.12, and its floor value is 2733.

2733

Python floor Division Example

When we perform division, the quotient may not be an integer. Therefore, we can either use the // operator or perform floor division. For instance, in the example below, the Mathematical “/” operator returns the remainder. Next, applied the math.floor() function on the result to see the floor division result. Otherwise, use the “//” operator for the floored result of the division.

# floor Division example
import math
a, b = 10, 3

x = a / b
print(x)
print(math.floor(x))

y = a // b
print(y)
3.3333333333333335
3
3

Python math.floor function on Data Structures

This section covers how to use the built-in floor() function on data structures, including lists, tuples, sets, and dictionaries.

Use the Python floor() function on lists

The following examples show how to use the math floor() function on a list of positive and negative floating-point numbers.

As we all know, a list is a group of items, so we can’t use the floor function directly on a list. Instead, we must use the index position to access individual items and apply the floor() function on them.

import math
x = [-22.45, 2.40, 9.65]
print("First = ", math.floor(x[0]))
print("Second = ", math.floor(x[1]))
print("Third = ", math.floor(x[2]))
First = -23
Second = 2
Third = 9

Using list comprehension

The following examples use list comprehensions to iterate over the list items. On each iteration, the Python math floor() function finds the largest number of each item that is less than the existing list element.

Here, the list contains the refund money list. Most companies trim the decimal places (cents) and pay the rounded amount to the end user. In such a scenario, the floor function always profits the companies by not paying the cents.

import math
refunds = [40.59, 90.42, 70.69, 12.89]
new = [math.floor(x) for x in refunds]
print(new)
[40, 90, 70, 12]

Using for lop

In this example, we use a for loop to iterate over the list items and then apply the Python math.floor() function on each item.

import math
numbers = [-10.89, 20.22, 40.67, -350.11, -450.91]
for num in numbers:
print(math.floor(num))
-11
20
40
-351
-451

Apart from the above mentioned options, we can use a lambda function. The example below is the same as the one above. However, this time we are using the map and Lambda functions to iterate over items.

import math
numbers = [-10.89, 20.22, 40.67, -350.11, -450.91]

floor_result = map(lambda num: math.floor(num), numbers)
print('The final result = ', list(floor_result))

The output of the math floor function, along with map and lambda functions, is shown below.

The final result =  [-11, 20, 40, -351, -451]

Python floor() function on Tuples

Similar to the lists, we can use the math floor() function on a tuple. Here, we must also use a loop to iterate over the tuple items and apply the floor function.

TIP: Use the index positions from 0 to n -1 to access individual items and apply the math.floor() function on them.

import math
numbers = (-2.45, 22.10, 22.95)

new = tuple(math.floor(x) for x in numbers)
print(new)
(-3, 22, 22)

By default, it creates a generator object, so we must use the tuple() function to convert the object to a tuple. Otherwise, use the for loop to iterate over tuples and apply the math.floor().

Python floor() function on Sets

In the example below, we use the math floor() function on sets to find the largest number of each set element that is less than or equal to the existing set elements.

As we all know, sets won’t allow any duplicates. If the floor value of any two set elements returns the same, the result contains only one, and the other item is deleted automatically. For instance, in the example below, the math.floor() function returns 22 for both 22.98 and 22.33, so the result consists of only one 22 (the other is removed).

import math
numbers = {11.77, 22.33, 22.98, 44.33}

new = {math.floor(x) for x in numbers}
print(new)
{11, 44, 22}

Python floor() function on Dictionaries

Along with the other data structures, we can use the math floor() function on dictionary values. In this example, users claim their tax refund for the financial year.

As most governments ignore the decimal values, they simply return the integer value without decimals. Here, the math.floor() helps the situation to pay the lower limit value. However, if the user has to pay, the system uses the ceil() function to pay the upper limit value.

import math
taxRefundUSD = {"user1": 120.98, "user2": 500.65, "user3": 90.99}

result = {users: math.floor(RefundValue)
for users, RefundValue in taxRefundUSD.items()}
print(result)
{'user1': 120, 'user2': 500, 'user3': 90}

Python math.floor() function in a NumPy array

The NumPy module has its own floor() function, which finds the largest number that is less than the existing number. We can apply the NumPy floor() function directly on ndarray.

Apart from the NumPy module, we can also use the math floor() function. However, we must use a for loop or another option to iterate over the ndarrays items and apply the math.floor() function on individual items.

In the example below, we show the math floor() function difference between the NumPy module and the math library. Here, we applied the NumPy ceil() function directly on the given array. On the other hand, we used list comprehension to iterate over the array elements and applied the math floor() function on individual items.

import numpy as np
import math
n = np.array([15.99, 25.88, 35.76, 45.45, 55.78])
print(np.floor(n))

result = [math.floor(i) for i in n]
print(result)

As you can see from the result below, the floor() method in both modules returns the same result. However, the NumPy module floor() returns a floating-point number, whereas the math module floor() returns an integer as the output.

[15. 25. 35. 45. 55.]
[15, 25, 35, 45, 55]

Python math.floor() function in Pandas DataFrame

When working with the DataFrame, it is always advisable to use the NumPy module floor() function. However, to find the floor value of a particular item or a small dataset, we can use math.floor() function.

In the example below, there are three mobile phone prices. As we all know, to attract customers, mobile companies always remove extra cents to please customers. In such a case, we can sue the math.floor() function.

import pandas as pd
import math

prices = {"Mobiles": ["iPhone", 'OnePlus','Samsung'],
"values": [999.89, 799.99, 899.56]}
data = pd.DataFrame(prices)

data["Floor"] = data["values"].apply(math.floor)
print(data)
   Mobiles  values  Floor
0   iPhone  999.89    999
1  OnePlus  799.99    799
2  Samsung  899.56    899

Python floor() vs ceil()

In the ceil() function article, we discussed the difference between ceil() and floor(), so please visit the article. In simple terms, the floor function rounds downwards. On the other hand, the ceil() function round upwards.

As you can see from the example below, the ceil() function returns the next integer, whereas the floor() returns the same integer without the decimal points. It means floor() moves towards 0, whereas the ceil() moves towards positive infinity.

import math

n = 100.67
print(math.floor(n))
print(math.ceil(n))
100
101

For a negative value, the floor() function moves towards negative infinity, whereas the ceil() function moves towards 0.

n = -200.12
print(math.floor(n))
print(math.ceil(n))
-201
200

Difference between Python floor() and int() function

Finding a difference between the floor() function and the int() method is the most frequently asked question on the internet. Both the int() and math floor() functions return the same result for positive values. However, if you check with negative values as an argument, then you can see the difference.

  • int() function always truncates toward zero. So, the integer value returned by int() always moves towards zero.
  • floor(): For positive numbers, it moves towards zero, and for negative numbers, it moves towards negative infinity.

Positive Numbers

As you can see from the above definition, for positive numbers, both the floor() and int() function moves towards zero and return the same result. So, the floor and int value of 200.99 is 200.

import math
n = 200.99

print(math.floor(n))
print(int(n))
200
200

Negative Numbers

For negative numbers, the int() function truncates the decimal values and returns the same number. It moves towards zero (-260 > -260.99). On the other hand, the floor() function moves towards negative infinity. Here, -261 is the largest number that is less than or equal to -260.99  (-261 < -260.99).

import math
n = -260.99
print(math.floor(n))
print(int(n))
-261
-260

Python floor() vs round()

The following table illustrates the difference between the math.floor() function and the round() method.

floor()round()
We must import the math module to utilize the floor() function.We don’t have to import anything to use the round() function.
math.floor(x)round(x, n)
The floor() function takes one parameter value and returns the largest integer value less than or equal to the given number.The round() function takes two arguments. It uses the famous 5 rule to round the number based on the optional second argument.
floor() return value is an integer.round() returns an int or float value based on 2nd parameter.
math.floor(40.6329) = 40round(40.6329) = 41
import math

n = 100.3628

print(math.floor(n))
print(round(n))
print(round(n, 1))
print(round(n, 2))
print(round(n, 3))
100
100
100.4
100.36
100.363

Custom code without using Python floor() function

The following example creates a custom floor function that can be used within a program without importing the math module or the math.floor() function.

  • n >= 0: For positive numbers, use the int() method to return the integer value of a given number.
  • For an integer input, return the same number.
  • For negative numbers, find the integer of it, and subtract one from it.
def customFloor(n):
if n >= 0:
return int(n)
else:
return int(n) if n == int(n) else int(n) - 1

print(customFloor(300.78))
print(customFloor(-500.78))
300
-501

You can also use the following custom function to return the floor value without using math.floor() function.

def customFloor(n):
    return int(n // 1)

Common Error of Python floor function

When working with math.floor() function, the following are some common errors we face.

NameError

If we miss the import module in the program, it won’t identify the math, so it will throw NameError.

In the following example, we missed the import math line at the beginning.

a = 30.89
print(math.floor(a))
NameError: name 'math' is not defined. Did you forget to import 'math'?

Fix: add the following line at the start

import math

Similarly, the code below also returns NameError because it does not identify the floor.

a = 30.89
print(floor(a))
NameError: name 'floor' is not defined. Did you mean: 'float'?

Fix: add the following line at the start

from math import floor

TypeError

The Python math floor() function only allows numerical values (floating-point numbers, integers, etc). However, in the example below, we used a string as the argument. So, the floor() method returns a TypeError.

import math
print(math.floor("15.78"))
TypeError: must be real number, not str

None argument

If we pass None value as the floor() function parameter, the program will throw a TypeError.

import math
print(math.floor(None))
TypeError: must be real number, not NoneType

ValueError

The math floor() function wont allow the not a number (NaN) as an argument, and if we pass NaN, it will return a ValueError.

import math
print(math.floor(float('nan')))
ValueError: cannot convert float NaN to integer

OverflowError

The math.floor() function wont allow the positive or negative infinity as the argument value, if we pass -inf or inf, it returns the OverflowError.

import math
print(math.floor(float('-inf')))
OverflowError: cannot convert float infinity to integer