Return an integer from integer division in Python

avatar

Borislav Hadzhiev

Last updated: Jul 11, 2022

banner

Photo from Unsplash

Return an integer from integer division in Python #

Use the floor division operator // to return an integer from integer division, e.g. result_1 = 30 // 6. The floor division operator will always return an integer and is like using mathematical division with the floor() function applied to the result.

main.py
result_1 = 30 // 6 print(result_1) # 👉️ 5 print(type(result_1)) # 👉️ <class 'int'> result_2 = 30 / 6 print(result_2) # 👉️ 5.0 print(type(result_2)) # 👉️ <class 'float'>

We used the floor division // operator to return an integer from int division.

Division / of integers yields a float, while floor division // of integers result in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

main.py
print(11 // 2) # 👉️ 5 print(11 / 2) # 👉️ 5.5

You can use the math.floor() method in a similar way to how we used the floor division // operator.

main.py
import math result_1 = math.floor(11 / 2) print(result_1) # 👉️ 5 result_2 = 11 / 2 print(result_2) # 👉️ 5.5

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

There is also a math.ceil() method.

main.py
import math result_1 = math.ceil(11 / 2) print(result_1) # 👉️ 6 result_2 = 11 / 2 print(result_2) # 👉️ 5.5

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

You can also use the round() function if you want to round to the nearest integer when dividing.

main.py
result_1 = round(15 / 4) print(result_1) # 👉️ 4 result_2 = 15 / 4 print(result_2) # 👉️ 3.75

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.

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.