Round a number to the nearest Integer in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Round a number to the nearest Integer in Python #

Use the round() function to round a number to the nearest integer, e.g. result = round(5.6). When called with a single argument, the round() function rounds the provided number to the nearest integer and returns the result.

main.py
result_1 = round(5.6) print(result_1) # 👉️ 6 result_2 = round(5.4) print(result_2) # 👉️ 5

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.
main.py
my_num = 3.579 result_1 = round(my_num) print(result_1) # 👉️ 4 result_2 = round(my_num, 2) print(result_2) # 👉️ 3.58

If you need to round a number to N digits precision, provide a value for the second argument in the call to round().

main.py
my_num = 3.45678 print(round(my_num, 2)) # 👉️ 3.46 print(round(my_num, 3)) # 👉️ 3.457 print(round(my_num, 4)) # 👉️ 3.4568

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

The round() function 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 up to the nearest integer, use the math.ceil() method.

main.py
import math print(math.ceil(3.001)) # 👉️ 4 print(math.ceil(3.889)) # 👉️ 4

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

If you need to round down to the nearest integer, use the math.floor() method.

main.py
import math print(math.floor(3.999)) # 👉️ 3 print(math.floor(3.001)) # 👉️ 3

The math.floor method returns the largest integer less than or equal to the provided number.

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.