How to remove the division decimal in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Remove the division decimal in Python #

Use the int() class to remove the division decimal, e.g. result = int(7 / 2). The int() class truncates floating-point numbers towards zero, so it will return an int that represents the number without the decimal places.

main.py
result_1 = int(7 / 2) print(result_1) # 👉️ 3 result_2 = int(-7 / 2) print(result_2) # 👉️ -3

We used the int() class to remove the division decimal.

The int class returns an integer object constructed from the provided number or string argument.

If passed a floating-point number, the int() class truncates towards zero.

This is exactly what we need because it allows us to remove the division decimal from a negative number in a way that suits our use case.

main.py
result_2 = int(-7 / 2) # 👉️ = -3.5 print(result_2) # 👉️ -3

Alternatively, you can use the floor division // operator.

Remove the division decimal using floor division #

Use the floor division // operator to remove the division decimal, e.g. result_1 = num_1 // num_2. The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

main.py
result_1 = 7 // 2 print(result_1) # 👉️ 3 result_2 = -7 // 2 print(result_2) # 👉️ -4
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
my_num = 50 print(my_num / 5) # 👉️ 10.0 (float) print(my_num // 5) # 👉️ 10 (int)

However, notice that when used with a negative number, the floor division // operator rounds towards negative infinity.

main.py
result_2 = -7 // 2 # 👉️ = -3.5 print(result_2) # 👉️ -4

This is different than the int() class, which rounds towards zero.

main.py
print(int(-7 / 2)) # 👉️ -3

An alternative to using the int() class is to use the math.trunc() method.

Remove the division decimal using math.trunc() #

Use the math.trunc() method to remove the division decimal, e.g. result = math.trunc(7 / 2). The math.trunc() method removes the fractional part and returns the integer part of the given number.

main.py
import math result_1 = math.trunc(7 / 2) print(result_1) # 👉️ 3 result_2 = math.trunc(-7 / 2) print(result_2) # 👉️ -3

The math.trunc method takes a number, removes its fractional part and returns its integer part.

The math.trunc() method rounds towards zero.

main.py
print(math.trunc(3.45)) # 👉️ 3 print(math.trunc(-3.45)) # 👉️ -3

This approach achieves the same result as passing the result from the division to the int() class.

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.