Ceil Function in Python – A Quick Guide

Filed Under: Python
Ceil Python

This tutorial will discuss using the ceil function with and without the Python math module. We’ll also look at some examples to know how they work exactly.

Also Read: Python Pandas math functions to know!

Introduction to Ceil Function

The Python math.ceil is a function that will round a given number up to the nearest integer. It works opposite of the floor function. The floor function rounds down a number to its lower nearest whole value whereas ceil function rounds a number up to its greater nearest whole value.

Recommended Read: Python Math

Code Implementation without math module

If we don’t want to use the math module, we can use use the code below to compute the ceil of a number.

def comp_ceil(n):
    return int(-1 * n // 1 * -1)

n = float(input("Enter Number : "))
print(n," to ceil is ",comp_ceil(n))

The integer division // goes to the next whole number to the left on the number line. By using -1, I switch the direction around to get the ceiling value, then use another *-1 to return to the original sign.

Let’s look at the output of code for both positive and negative numbers.

Enter Number: 5.8
5.8  to ceil is  6
Enter Number: -4.8
-4.8  to ceil is  -4

Code Implementation of Ceil using math module

The Python math module comes with the ceil function which can help to calculate the ceil of a number. The math.ceil function takes in one parameter (the number whose ceil value is required). On the first line, we import the math library, and then we take the number from the user in the variable n. Then, we use math.ceil function to round down the variable, n to its nearest whole number.

Look at the code snippet below.

import math
n = float(input("Enter Number : "))
print(n," to ceil is ",math.ceil(n))

Below is a sample output of the code above.

Enter Number : 3.9
3.9  to ceil is  4

Let’s look at how the code works for the negative values below.

Enter Number : -5.9
-5.9  to ceil is  -5

Conclusion

The Python ceil method allows you round a number down to its nearest whole integer. This tutorial discussed using both the math function with and without the math module.

Thank you for reading!

Recommended Read: 4 Ways to handle Precision values in Python

close
Generic selectors
Exact matches only
Search in title
Search in content