在 Python 中将浮点数转换为整数
由于内置函数和库,在 Python 中将浮点数转换为整数相对容易。将浮点数转换为整数时,有两种可能性。尽管自己编写函数来完成此任务很容易,但在本文中我们仅讨论如何使用内置函数和库。
假设我们有一个数字,例如 1.52
。如果我们希望将该数字转换为整数,则可以使用 2
或 1
。前者是最高值,后者是最低值。由于有多个函数来完成这个任务,因此它们都以不同的方式执行上述任务并返回不同的值。因此,请根据你的用例选择相应的函数。
在 Python 中使用 int()
函数将浮点数转换为整数
number = 25.49
print(int(number))
输出:
25
int()
函数接受表示数字的参数并将其转换为整数。此参数可以是字符串,浮点值或整数本身。该函数考虑数字中的整数值或小数点前的部分,然后将其返回。
但是,当以整数形式 integer.9999999999999999
作为参数传递时,int()
的行为略有不同。如果小数点后有十六个以上的 9
位数,则在返回正数的情况下该函数将返回整数+1
,而在负数的情况下该函数将返回整数-1
作为答案。
请参考以下代码片段,以更好地理解该概念。
print(int(1.5))
print(int(1.51))
print(int(1.49))
print(int(-1.5))
print(int(-1.51))
print(int(-1.49))
print(int(1.9999999999999999))
print(int(-1.9999999999999999))
输出:
0
1
1
1
1
-1
-1
-1
2
-2
使用 Python 中的 math
模块将浮点数转换为整数
我们可以使用内置的 Python 库 math
来完成相同的任务。该库具有数学计算所需的各种数学函数。
我们将只讨论 math
库中的三个数学函数。
顾名思义,trunc()
函数会截断或删减作为参数传递的数字的小数部分,而只考虑整数部分。它的行为与内置的 int()
函数完全相同,对于我们上面谈到的例外情况,它的行为是不同的。
import math
print(math.trunc(0))
print(math.trunc(1))
print(math.trunc(1.5))
print(math.trunc(1.51))
print(math.trunc(1.49))
print(math.trunc(-1.5))
print(math.trunc(-1.51))
print(math.trunc(-1.49))
print(math.trunc(1.9999999999999999))
print(math.trunc(-1.9999999999999999))
输出:
0
1
1
1
1
-1
-1
-1
2
-2
接下来,我们有 ceil()
函数。此函数返回数字的上限值或大于或等于作为参数传递的数字的最小整数。
import math
print(math.ceil(0))
print(math.ceil(1))
print(math.ceil(1.5))
print(math.ceil(1.51))
print(math.ceil(1.49))
print(math.ceil(-1.5))
print(math.ceil(-1.51))
print(math.ceil(-1.49))
print(math.ceil(1.9999999999999999))
print(math.ceil(-1.9999999999999999))
输出:
0
1
2
2
2
-1
-1
-1
2
-2
最后,我们具有 floor()
函数。此函数返回数字的下限值或小于或等于作为参数传递的数字的最大整数。
import math
print(math.floor(0))
print(math.floor(1))
print(math.floor(1.5))
print(math.floor(1.51))
print(math.floor(1.49))
print(math.floor(-1.5))
print(math.floor(-1.51))
print(math.floor(-1.49))
print(math.floor(1.9999999999999999))
print(math.floor(-1.9999999999999999))
输出:
0
1
1
1
1
-2
-2
-2
2
-2
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。