Floor Function in Python – A Quick Guide

Filed Under: Python
Floor Python

This tutorial will discuss using the floor method to return the floor of a provided value. We’ll also look at some examples to know how they work exactly.

Also Read: Python Pandas math functions to know!

Introduction to Floor Function

The Python math.floor function rounds a given number down to the nearest integer which is less or equal to the number. In other words, the floor of a number is the number rounded down to its nearest integer value.

Recommended Read: Python Math

Comparison with the round function

The Python round function searches for the nearest number, which could include decimals, on the other hand, math.floor function rounds to the nearest integer.

Code Implementation of Floor using the math module

The Python math module comes with the floor function which can help to calculate the floor of a number. The math.floor function takes in one parameter (the number whose floor value is required).

On the first line, we import the math library, and then we take the number from the user in the variable n. Then, we use math.floor function to round down the variable, n to its nearest whole number.

Look at the code snippet below.

import math
n = float(input("Enter Number : "))
print(n," to floor is ",math.floor(n))

Our code returns the smallest integer closest to n ( user input number). Below is a sample output of the code above.

Enter Number : 3.9
3.9  to floor is  3

Let’s look at how the code works for the negative values below.

Enter Number : -5.9
-5.9  to floor is  -6

Code Implementation without math module

If we don’t want to use the math module, we can use use the code below to compute the floor of a number.

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

n = float(input("Enter Number : "))
print(n," to floor is ",comp_floor(n))

The integer division //, goes to the next whole number to the left on the number line. Lets look at the output of code for both positive and negative numbers.

Enter Number : 5.8
5.8  to floor is  5
Enter Number : -4.8
-4.8  to floor is  -5

Conclusion

The Python floor method allows you round a number down to its nearest whole integer. This tutorial discussed using both the math function with and without the math module.

Thank you for reading!

Recommended Read: 4 Ways to handle Precision values in Python

close
Generic selectors
Exact matches only
Search in title
Search in content