在Python中将float或int转换为最接近的整数的最简单方法

时间:2014-07-18 23:04:16

标签: python math type-conversion

我想定义一个函数,它可以将整数或浮点数作为参数,并返回最接近的整数(即输入参数本身,如果它已经是整数)。我试过这个:

 def toNearestInt(x):
    return int(x+0.5)

但它对负整数不起作用。

>>> toNearestInt(3)
3
>>> toNearestInt(3.0)
3
>>> toNearestInt(3.49)
3
>>> toNearestInt(3.50)
4
>>> toNearestInt(-3)
-2

我该如何解决?

2 个答案:

答案 0 :(得分:4)

Python已经内置了这个(或多或少)。

>>> round(-3, 0)
-3.0
>>> round(-3.5, 0)
-4.0
>>> round(-3.4, 0)
-3.0
>>> round(-4.5, 0)
-5.0
>>> round(4.5, 0)
5.0

当然,您可能希望将其包含在int ...

的调用中
def toNearestInt(x):
    return int(round(x, 0))

答案 1 :(得分:2)

您可以在此处保留初始方法,只需检查输入是否为负数,并在这种情况下添加-0.5。

def toNearestInt(x):
    a = 0.5
    if x < 0:
        a*=-1
    return int(x+a)