Python: 将'3.5'转换为整数

2 投票
4 回答
7833 浏览
提问于 2025-04-16 08:39

到目前为止,我会这样做:int(float('3.5'))

还有其他好的方法吗?

注意:3.5是一个字符串。

我想使用专门为这种问题提供的内置API。

4 个回答

1

你只需要用这个代码:int(3.5)

注意,这个操作是截断的,不是四舍五入哦。

4

你现在的代码已经是最简单、最清晰的了,可能唯一比这更简单的代码是 int('3.5'),但这个代码是不能运行的。所以,你的代码就是最简单、最明了的有效代码。

5

你走在正确的道路上,最好的解决方案可能就是上面提到的:

>>> int(float("3.5"))

这个方法会把小数部分去掉。

如果你想要不同的四舍五入方式,可以使用 math 这个库:

>>> import math
>>> x = "3.5"
>>> math.floor(float(x)) # returns FP; still needs to be wrapped in int()
3.0
>>> math.ceil(float(x)) # same
4.0
>>> math.trunc(float(x)) # returns an int; essentially the same as int(float(x))
3

另一方面,如果你想把数字四舍五入到最接近的整数,可以在转换为整数之前使用内置的 round 函数,比如:

>>> int(round(float(x))) # 3.5 => 4
4
>>> int(round(3.4999))
3

撰写回答