繁体   English   中英

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

[英]simplest way to convert either a float or an int to the nearest integer in Python

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

 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

我该如何解决?

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))

您可以在这里保留最初的方法,仅检查输入是否为负数,然后添加-0.5即可。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM