你是在正确的轨道上,最好的解决方案可能是如上所述:
>>> int(float("3.5"))
Run Code Online (Sandbox Code Playgroud)
这会截断浮动.
如果您想要不同类型的舍入,可以使用该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
Run Code Online (Sandbox Code Playgroud)
另一方面,如果您希望将数字四舍五入为最接近的整数,则可以round在转换为整数之前使用浮点内置操作,例如
>>> int(round(float(x))) # 3.5 => 4
4
>>> int(round(3.4999))
3
Run Code Online (Sandbox Code Playgroud)