There are three ways you can remove the decimal from a floating point number in Python. Depending on what you want to accomplish, any of these ways might work for you.
The first way is to use the Python round() function.
num = 1.53
print(round(num))
#Output:
2
You can also use the Python math module trunc() function.
import math
num = 1.53
print(math.trunc(num))
#Output:
1
One last way is to use the Python int() function.
num = 1.53
print(int(num))
#Output:
1
When working with numbers, the ability to easily format and change the value of different numbers can be valuable.
One such situation is if you are working with decimal numbers or floating point numbers and want to remove the decimal.
In Python, there are a few different ways to remove the decimal numbers.
Depending on what you want to do, you can use any of these methods to remove the decimals.
For example, the Python int() function converts a float to an integer and simply removes the decimal portion of the number. The math module trunc() function has the same behavior.
Below is an example showing how you can remove the decimal from a floating point number with the int() and trunc() functions.
import math
num_1 = 1.53
num_2 = -6.12
num_3 = 100.2341
print(math.trunc(num_1))
print(int(num_1))
print(math.trunc(num_2))
print(int(num_2))
print(math.trunc(num_3))
print(int(num_3))
#Output:
1
1
-6
-6
100
100
As you can see, int() and trunc() simply removes the decimal portion from the numbers with decimals.
If you are looking to take into consideration the decimal portion part of the number, then you can use the Python round() function. round() rounds a number to the nearest integer.
Below shows you an example of how to remove the decimal from a number with round() in Python.
num_1 = 1.53
num_2 = -6.12
num_3 = 100.2341
print(round(num_1))
print(round(num_2))
print(round(num_3))
#Output:
2
-6
100
Hopefully this article has been useful for you to understand how to remove decimals from numbers in Python.