Python trunc

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

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, Python truncate function returns the TypeError.

Python trunc Function Example

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

# Python TRUNC Function
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

Within this truncate function example,

  1. First two statements, We used the python truncate Function directly on both the Positive decimals 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 is working perfectly on them.
  3. Next statement, We tried Python trunc Function with multiple values
  4. In the last statement, we tried math truncate Function on the String value. As we said before, it returns TypeError: type str doesn’t define __trunc__ method as output.