Cover Image for floor() and ceil() Functions in Python
174 views

floor() and ceil() Functions in Python

The Python floor() and ceil() functions are commonly used for rounding numbers, particularly floating-point numbers, to the nearest integer values. These functions are part of the math module, so you need to import the math module to use them.

  1. math.floor() Function:
  • The math.floor() function rounds a floating-point number down to the nearest integer that is less than or equal to the original number.
  • It always returns a value that is less than or equal to the input number.
   import math

   number = 5.7
   rounded_down = math.floor(number)

   print(rounded_down)  # Output: 5

In this example, math.floor(5.7) rounds down to 5.

  1. math.ceil() Function:
  • The math.ceil() function rounds a floating-point number up to the nearest integer that is greater than or equal to the original number.
  • It always returns a value that is greater than or equal to the input number.
   import math

   number = 5.2
   rounded_up = math.ceil(number)

   print(rounded_up)  # Output: 6

In this example, math.ceil(5.2) rounds up to 6.

These functions are particularly useful when you need to work with whole numbers and want to ensure that the result is rounded in a specific direction. They are commonly used in mathematical and scientific calculations where precision is important.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS