如何在 Python 中将浮点数转换为整数

2024 年 8 月 29 日 | 4 分钟阅读

我们在 Python 中使用过不同的数字数据类型,在本教程中,我们将学习如何将浮点值转换为整数值。

让我们来看看实现此目标的几种方法:

  1. 使用 trunc()
  2. 使用 floor()
  3. 使用 ceil()
  4. 使用 int()

那么,让我们开始第一个吧-

使用 trunc()

以下程序展示了如何在 Python 中使用 trunc() 将浮点值转换为整数。

输出

The result of a + b + c is 42.33
The converted value of a is: 20
The converted value of b is: 12
The converted value of c is: 9
The converted value of sum is: 42

说明:

是时候理解上面程序中发生了什么了-

  1. 由于我们需要使用 trunc(),因此我们在第一步导入了 math 模块。
  2. 在此之后,我们初始化了三个浮点值,然后计算了它们的和。
  3. 最后,我们将变量 a、b、cres_sum 传递给 trunc() 以获得整数值。
  4. 执行程序后,我们将获得所需的输出。

在下一个程序中,我们将使用 floor()。

使用 floor()

首先,让我们了解一下将浮点值传递给 floor() 时会发生什么?

当一个浮点数被传递给 floor() 时,它会将数字向下舍入到最近的整数。

考虑下面的程序,

输出

The result of a + b + c is 42.33
The converted value of a is: 20
The converted value of b is: 12
The converted value of c is: 9
The converted value of sum is: 42

说明:

让我们看一眼这个程序的解释。

  1. 由于我们需要使用 floor(),因此我们在第一步导入了 math 模块。
  2. 在此之后,我们初始化了三个浮点值,然后计算了它们的和。
  3. 最后,我们将变量 a、b、cres_sum 传递给 floor() 以获得整数值。
  4. 执行程序后,我们将获得所需的输出。

现在,我们将看看如何使用 ceil() 来实现相同的目的。

使用 ceil()

首先,让我们了解一下将浮点值传递给 ceil() 时会发生什么?

当一个浮点数被传递给 ceil() 时,它会将数字向上舍入到最近的整数。

输出

The result of a + b + c is 42.33
The converted value of a is: 21
The converted value of b is: 13
The converted value of c is: 10
The converted value of sum is: 43

说明:

让我们了解一下我们在这个程序中做了什么。

  1. 由于我们需要使用 ceil(),因此我们在第一步导入了 math 模块。
  2. 在此之后,我们初始化了三个浮点值,然后计算了它们的和。
  3. 最后,我们将变量 a、b、cres_sum 传递给 ceil() 以获得整数值。
  4. 执行程序后,我们将获得所需的输出。

最后,在最后一个程序中,我们将使用将浮点值转换为整数的最基本方法,即使用 int()

使用 int()

下面的程序说明了如何在程序中使用它。

输出

The result of a + b + c is 42.33
The converted value of a is: 20
The converted value of b is: 12
The converted value of c is: 9
The converted value of sum is: 42

说明:

  1. 我们初始化了三个浮点值,然后计算了它们的和。
  2. 最后,我们将变量 a、b、c 和 res_sum 传递给 int() 以获得整数值。
  3. 执行程序后,我们将获得所需的输出。

结论

在本教程中,我们学习了在 Python 中将浮点数转换为整数的有趣方法。