当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python math.trunc()用法及代码示例

Python math.trunc() 方法

math.trunc() 方法是 math 模块的库方法,用于获取一个数的截断整数值,它接受一个数(整数或浮点数)并返回截断为整数的实数。

注意:如果传递除数字以外的任何内容,则该方法返回类型错误,如果我们传递一个字符串 - 它将返回“TypeError:type str 未定义 __trunc__ 方法”

math.trunc() 方法的语法:

    math.trunc(n)

参数: n– 整数或浮点数。

返回值: int– 它返回一个整数值,它是数字的整数部分n

例:

    Input:
    a = 10.23

    # function call
    print(math.trunc(a))

    Output:
    10

用于演示 math.trunc() 方法示例的 Python 代码

# Python code demonstrate example of 
# math.trunc() method

# importing math module
import math

# numbers 
a = 10
b = 10.23
c = -10
d = -10.67
e = 10.67

# printing the fractional and integer part 
# of the numbers by using math.trunc()

print("trunc(a):", math.trunc(a))
print("trunc(b):", math.trunc(b))
print("trunc(c):", math.trunc(c))
print("trunc(d):", math.trunc(d))
print("trunc(e):", math.trunc(e))

输出

trunc(a): 10
trunc(b): 10
trunc(c): -10
trunc(d): -10
trunc(e): 10


相关用法


注:本文由纯净天空筛选整理自 math.trunc() method with example in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。