The ceil() is a built-in math module function in Python that “rounds up a number to the nearest integer and returns the result”. The ceil() method accepts only one input value, the numeric value, and returns the rounded-up value to the nearest integer.
To round up numbers in Python, you can use the “math.ceil()” function.
What does it mean to round up?
To round up means you round a number to the closest integer. This means if your given number is 5.1. it will round up to 6.
When you round up a number, you round the number to the closest integer greater than the number.
The time complexity of ceil() function
The ceil() function has a time complexity of O(1), which means it takes a fixed amount of time to execute regardless of the size of an input value.
How to use ceil() function?
To use the ceil() function in Python, import the math module.
Syntax
math.ceil(num)
Parameter values
The math.ceil() function accepts a num as an argument.
Return value
The ceil() function returns an int value representing the rounded number.
Example 1
import math
print(math.ceil(1.9))
print(math.ceil(2.1))
print(math.ceil(11.1))
print(math.ceil(21.19))
Output
2
3
12
22
You can see that the ceil() function rounds up the 1.9 number to 2. Then, 2.1 to 3, 11.1 to 12, and 21.19 to 22.
How to round up to 2 decimal places using ceil()
To round up two decimal places in Python, you can use the “math.ceil()” function.
import math
num = 0.222222222000
num = math.ceil(num * 100) / 100.0
print(num)
Output
0.23
You can see that we rounded up to two decimal places from 0.22222222000 to 0.23.
What is the difference between Python floor() and ceil()?
The main difference between the “floor()” and “ceil()” functions is that floor() function rounds down to its nearest integer value, and ceil() function rounds up to its nearest integer.
Pros and Cons of ceil() function
Pros
- It has a fast execution time.
- The math.ceil() is a built-in function, so you don’t need to install other libraries.
- The math.ceil() is not a complex function with many arguments; it is an easy-to-use function that takes several arguments and returns the result.
Cons
- It rounds up to the nearest integer, which you can’t do with other types of rounding.
- You can use either the “floor()” or “round()” function for other rounding tasks because ceil() is not useful for every scenario.
That’s it.