Python 中的 trunc 函数(或 truncate 函数)用于从指定的表达式中删除小数部分,并返回整数值。在本节中,我们将通过一个示例讨论如何在 Python 编程语言中使用 trunc 函数,其语法如下所示。
math.trunc(number);
Number:这是您想要截断的小数或有效的数值表达式。如果 number 参数不是数字,该函数将返回 TypeError。
Python trunc 或 truncate 函数示例
math 函数允许您从指定的表达式中删除小数部分并返回整数值。在此示例中,我们将使用 trunc 函数查找不同数据类型的截断值并显示输出。
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'))

在此示例中,
- 在前两个 trunc 语句中,我们直接对正数和负数小数使用了 Python truncate 函数。
- 在接下来的四个语句中,我们对元组和列表项使用了 trunc 函数。如果您观察上面的 Python 屏幕截图,这个 math 函数在它们上运行得非常好。
- 在下一个语句中,我们尝试将其用于多个值。
- 在最后一个语句中,我们尝试将 math 函数用于字符串值。正如我们之前所说,它返回 TypeError: type str doesn’t define __trunc__ method 作为输出。