Python math.trunc()方法

Pythonmath.trunc() 方法是截断一个数字的整数部分的有效方法。x 对于负数,它表现为ceil() 函数,对于正数,它表现为floor() 函数x

如果指定的数字已经是一个整数,则返回相同的数字。

Pythonmath.trunc() 方法的语法

math.trunc(x)

参数

x 任何正数或负数。

返回

该方法返回一个整数,代表x 的截断整数部分。

例1:对负数使用math.trunc() 方法

import math
x=-2.29876
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
x=-10
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
x=-3.001
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")

输出:

The truncated integer part of -2.29876 is -2.
The truncated integer part of -10 is -10.
The truncated integer part of -3.001 is -3.

请注意,该方法返回的负数值相当于math.ceil()

例2:对正数使用math.trunc() 方法

import math
x=3.45
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
x=10
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
x=132.00006
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")

输出:

The truncated integer part of 3.45 is 3.
The truncated integer part of 10 is 10.
The truncated integer part of 132.00006 is 132.

请注意,此方法返回的正数值相当于math.floor()

例3:使用math.trunc() 方法时的错误

import math
##entering a string
x="Hi"
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
##entering a list
x=[1,2,3]
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
##entering complex numbers
x=1+5j
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")
##entering an infinite number
x=math.inf
value=math.trunc(x)
print(f"The truncated integer part of {x} is {value}.")

输出:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    value=math.trunc(x)
TypeError: type str doesn't define __trunc__ method
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    value=math.trunc(x)
TypeError: type list doesn't define __trunc__ method
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    value=math.trunc(x)
TypeError: type complex doesn't define __trunc__ method
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    value=math.trunc(x)
OverflowError: cannot convert float infinity to integer

上面的代码片断显示了使用math.trunc() 方法时可能出现的所有语法错误。