Get number without decimal places in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Get number without decimal places in Python #

Use the int() class to get a number without the decimal places, e.g. result = int(my_float). 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
my_float = 3.14 result = int(my_float) print(result) # 👉️ 3 my_float_2 = -3.14 result_2 = int(my_float_2) print(result_2) # 👉️ -3

We used the int() class to get a number without the decimal places.

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 get a negative number without the decimal places.

main.py
my_float_2 = -3.14 result_2 = int(my_float_2) print(result_2) # 👉️ -3

You might see examples online that use the math.floor() method in this scenario.

However, the math.floor() method truncates toward negative infinity.

main.py
import math print(math.floor(5.345)) # 👉️ 5 print(math.floor(-5.345)) # 👉️ -6

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

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

Get number without decimal places using math.trunc() #

Use the math.trunc() method to get a number without the decimal places, e.g. result = math.trunc(my_float). The math.trunc() method removes the fractional part and returns the integer part of the given number.

main.py
import math my_float = 5.345 result_1 = math.trunc(my_float) print(result_1) # 👉️ 5 my_float_2 = -5.345 result_2 = math.trunc(my_float_2) # 👉️ -5 print(result_2)

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
import math print(math.trunc(2.468)) # 👉️ 2 print(math.trunc(-2.468)) # 👉️ -2

Since the math.trunc() method rounds towards zero, it handles negative numbers in a way that suits our use case.

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.