Round a number UP to the nearest integer in Python

avatar

Borislav Hadzhiev

Last updated: Jul 11, 2022

banner

Photo from Unsplash

Round a number UP to the nearest integer in Python #

Use the math.ceil() method to round a number up to the nearest integer, e.g. result = math.ceil(3.001). The math.ceil method returns the smallest integer greater than or equal to the provided number.

main.py
import math result_1 = math.ceil(3.001) print(result_1) # 👉️ 4 result_2 = math.ceil(3.988) print(result_2) # 👉️ 4

We used the math.ceil() method to round a number up to the nearest integer.

main.py
import math print(math.ceil(13.0001)) # 👉️ 14 print(math.ceil(15.4444)) # 👉️ 16 print(math.ceil(19.9999)) # 👉️ 20

The math.ceil method returns the smallest integer greater than or equal to the provided number.

Make sure to store the result from calling math.ceil() in a variable.

The math.ceil() method doesn't change the original number, it returns a new number. Values of type int and float (and all other primitives) are immutable in Python.

If you need to round to the nearest integer (up or down), use the round() function.

main.py
print(round(4.6)) # 👉️ 5 print(round(4.4)) # 👉️ 4

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal, the number should have after the operation (optional)

The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

If you use the numpy module, you can also use the numpy.ceil() method to save yourself a math import.

main.py
import numpy as np result_1 = np.ceil(3.0001) print(result_1) # 👉️ 4.0 result_2 = np.ceil(3.9987) print(result_2) # 👉️ 4.0

The numpy.ceil method returns the ceiling of the input.

The only good reason to use numpy.ceil() instead of math.ceil(), in this scenario, is if you already have numpy imported in the specific module.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.