The Python math module trunc() function returns the truncated integer part of a floating point number. You can use trunc() to truncate the decimal of a floating point number in Python.
import math num = 1.53 print(math.trunc(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 truncate the decimal.
The Python math module has many powerful functions which make performing certain calculations in Python very easy.
The math module trunc() function allows you to truncate a decimal number and converts a float to an integer by simply removing the decimal portion of the number.
Below are some examples showing how you can truncate the decimal from a floating point number with the trunc() function.
import math num_1 = 1.53 num_2 = -6.12 num_3 = 100.2341 print(math.trunc(num_1)) print(math.trunc(num_2)) print(math.trunc(num_3)) #Output: 1 -6 100
As you can see, trunc() simply removes the decimal portion from the numbers with decimals.
Truncating Decimal with int() and round() Functions in Python
There are two other ways you can truncate a decimal in Python. The Python int() function removes the decimal from a number in the same way as trunc().
import math num_1 = 1.53 num_2 = -6.12 num_3 = 100.2341 print(int(num_1)) print(int(num_2)) print(int(num_3)) #Output: 1 -6 100
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 truncate a decimal and get the integer portion of a number in Python.