Python math.ceil() function


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

Syntax

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

Return Value

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

Examples

  1. Rounding up a positive float:

    import math result = math.ceil(4.2) print(result) # Output: 5
  2. Rounding up a negative float:

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

    result = math.ceil(5) print(result) # Output: 5
  4. Rounding up a float that is already an integer:

    result = math.ceil(8.0) print(result) # Output: 8
  5. Using math.ceil() with complex expressions: You can use math.ceil() in expressions:

    a = 2.3 b = 3.8 result = math.ceil(a + b) print(result) # Output: 6
  6. Rounding very small decimal numbers:

    result = math.ceil(0.1) print(result) # Output: 1

Summary

  • The math.ceil() function returns the smallest integer greater 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 up, such as calculating the number of pages needed for a certain number of items per page.