In Python, the floor() function is a built-in math library function that takes a number as an argument and returns the largest integer that is not greater than the number given. The floor() function is responsible for rounding off decimal numbers to an integer value less than the number provided as the argument.
Syntax
math.floor(x)
Parameters
The math.floor() method takes x as a numeric number, a required parameter.
How the floor() function works in Python
The floor() function in Python returns the largest integer less than or equal to a given number. It is a part of the math module in Python and can be used as follows: “math.floor(number)”.
For example:
- math.floor(4.6) will return 4
- math.floor(-4.6) will return -5
The floor function rounds down the number to the nearest integer, so if the number is positive, it returns the largest integer less than the number, and if the number is negative, it returns the smallest integer greater than the number.
Examples of using floor function in Python
Example 1
import math
caltech = math.floor(300.72)
print(caltech)
Example 2
import math
print("math.floor(-19.21): ", math.floor(-19.21))
print("math.floor(19.46): ", math.floor(19.46))
print("math.floor(46.19): ", math.floor(46.19))
Output
Real-life examples to demonstrate the practical applications of floor function
Using the floor() function to round down 2 decimal places
To round down two decimal places in Python, use math.floor() function.
Divide the math.floor() function’s output by 100.0, and you will get the floor value to 2 decimal places.
import math
data = 19.2110
print(math.floor(data * 100) / 100.0)
Output
19.21
How to get the floor without a math module
To calculate floor without math in Python, use the double-backslash (//) operator.
The double-slash operator is used for “floor” division which rounds down to the nearest whole number.
print(3 // 2)
Output
1
What is floor division in Python?
Floor division is an operation that divides two numbers and rounds the result down to the nearest integer.
To perform floor division in Python, use the double-backslash (//) operator.
print(5 // 3)
Output
1
Floor division means dividing and rounding down to the nearest integer. In the above example, the rounding down to the nearest integer is 1; that’s why the output is 1.
That’s it.