Python trunc

The Python trunc function or truncate function is used to remove the decimal values from specified expressions and returns the integer value. In this section, we discuss how to use trunc function in Python Programming language with an example, and the syntax of the Truncate is shown below.

math.trunc(number);

Number: It can be a decimal or a valid numerical expression on which you want to Truncate. If the number argument is not a number, the function returns the TypeError.

Python trunc or truncate Function Example

The math Function allows you to remove the decimal values from specified expressions and return the integer value. In this Python example, We are going to find the truncated values of different data types using the trunc function and display the output.

import math

Tup = (10.98, 20.26, 30.05, -40.95 , 50.85) # Tuple Declaration
Lis = [-10.98, 32.65, -39.29, -42.15 , -39.97] # List Declaration

print('TRUNC() Function on Positive Decimal = %d' %math.trunc(10.98763))
print('TRUNC() Function on Negative Decimal = %d' %math.trunc(-15.48476))

print('TRUNC() Function on Tuple Item = %d' %math.trunc(Tup[2]))
print('TRUNC() Function on Tuple Item = %d' %math.trunc(Tup[4]))
print('TRUNC() Function on List Item = %d' %math.trunc(Lis[2]))
print('TRUNC() Function on List Item = %d' %math.trunc(Lis[4]))

print('TRUNC() Function on Multiple Number = %d' %math.trunc(10 + 20 - 40.6578))

print('TRUNC() Function on String Value = ', math.trunc('2.95'))
Python TRUNC Function to truncate

Within this example,

  1. First two trunc statements, We used the Python truncate Function directly on both positive and negative decimals.
  2. Following four statements, We used the trunc Function on Tuple and List items. If you observe the above Python screenshot, this Math function works perfectly on them.
  3. Next statement, We tried it with multiple values.
  4. In the last statement, we tried the math Function on the String value. As we said before, it returns TypeError: type str doesn’t define __trunc__ method as output.