迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/12/21 浏览次数:

由于内置函数和库,在 Python 中将浮点数转换为整数相对容易。将浮点数转换为整数时,有两种可能性。尽管自己编写函数来完成此任务很容易,但在本文中我们仅讨论如何使用内置函数和库。

假设我们有一个数字,例如 1.52。如果我们希望将该数字转换为整数,则可以使用 21。前者是最高值,后者是最低值。由于有多个函数来完成这个任务,因此它们都以不同的方式执行上述任务并返回不同的值。因此,请根据你的用例选择相应的函数。


在 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

请参阅官方文档以了解有关此函数的更多信息,此处

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便