Python math.floor() function


The math.floor() function in Python is used to return the largest integer that is less than or equal to a given number. This function is useful when you need to round a floating-point number down to the nearest whole number.

Syntax

import math result = math.floor(x)
  • x: A numeric expression (integer or float) for which you want to find the floor value.

Return Value

  • Returns the largest integer less than or equal to x, which is of type int.

Examples

  1. Rounding down a positive float:

    import math result = math.floor(4.8) print(result) # Output: 4
  2. Rounding down a negative float:

    result = math.floor(-3.2) print(result) # Output: -4
  3. Rounding an integer: If you pass an integer to math.floor(), it will return the integer itself.

    result = math.floor(7) print(result) # Output: 7
  4. Rounding down a float that is already an integer:

    result = math.floor(5.0) print(result) # Output: 5
  5. Using math.floor() with complex expressions: You can use math.floor() in expressions:

    a = 3.9 b = 2.1 result = math.floor(a + b) print(result) # Output: 6
  6. Rounding very small decimal numbers:

    result = math.floor(0.7) print(result) # Output: 0

Summary

  • The math.floor() function returns the largest integer less than or equal to the input value.
  • It works with both integers and floating-point numbers.
  • The return type is always int.
  • This function is particularly useful in scenarios where you need to ensure that a value is rounded down, such as calculating the number of items that can fit into a fixed number of containers or pages.