Borislav Hadzhiev
Last updated: Jul 11, 2022
Photo from Unsplash
Use the floor division operator //
to divide without a remainder, e.g.
result_1 = 25 // 4
. The floor division operator will always return an integer
and is like using mathematical division with the floor()
function applied to
the result.
result_1 = 25 // 4 print(result_1) # 👉️ 6 result_2 = 25 / 4 print(result_2) # 👉️ 6.25
We used the floor division //
operator to divide without a remainder.
/
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.
my_num = 50 print(my_num / 5) # 👉️ 10.0 (float) print(my_num // 5) # 👉️ 10 (int)
You can use the math.floor()
method in a similar way to how we used the floor
division //
operator.
import math result_1 = math.floor(25 / 4) print(result_1) # 👉️ 6 result_2 = 25 / 4 print(result_2) # 👉️ 6.25
The math.floor method returns the largest integer less than or equal to the provided number.
There is also a math.ceil()
method.
import math result_1 = math.ceil(25 / 4) print(result_1) # 👉️ 7 result_2 = 25 / 4 print(result_2) # 👉️ 6.25
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.
result_1 = round(26 / 4) print(result_1) # 👉️ 6 result_2 = 26 / 4 print(result_2) # 👉️ 6.5 # -------------------------------- print(round(6.5)) # 👉️ 6 print(round(6.51)) # 👉️ 7
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the 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.