Python math.trunc() 方法



Python 的 math.trunc() 方法用于将浮点数截断为最接近零的整数。截断是指删除数字的小数部分,而不进行四舍五入。

例如,math.trunc(3.14) 将返回 3,而 math.trunc(-3.14) 将返回 -3 作为结果。

语法

以下是 Python math.trunc() 方法的基本语法:

math.trunc(x)

参数

此方法接受一个数值(浮点数或整数)作为参数,您希望将其截断为最接近零的整数。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

返回值

该方法返回一个整数,表示给定值“x”的截断值。

示例 1

在以下示例中,我们使用 math.trunc() 方法截断浮点数“10.9”:

Open Compiler
import math result = math.trunc(10.9) print("The result obtained is:",result)

输出

获得的输出如下:

The result obtained is: 10

示例 2

在这里,我们使用 math.trunc() 方法截断负浮点数“-10.9”:

Open Compiler
import math result = math.trunc(-10.9) print("The result obtained is:",result)

输出

以下是上述代码的输出:

The result obtained is: -10

示例 3

现在,我们截断浮点数“15.0”。由于没有小数部分,因此结果保持不变:

Open Compiler
import math result = math.trunc(15.0) print("The result obtained is:",result)

输出

我们得到如下所示的输出:

The result obtained is: 15

示例 4

在此示例中,我们使用变量“x”存储浮点数“3.14159”。然后我们将“x”截断为最接近的整数:

Open Compiler
import math x = 3.14159 result = math.trunc(x) print("The result obtained is:",result)

输出

产生的结果如下所示:

The result obtained is: 3
python_maths.htm
广告