[英]simplest way to convert either a float or an int to the nearest integer in Python
I want to define a function that can take either an integer or a floating-point number as an argument, and return the nearest integer (ie the input argument itself if it is already an integer). 我想定义一个函数,该函数可以接受整数或浮点数作为参数,并返回最接近的整数(即输入参数本身已经是整数)。 I tried this:
我尝试了这个:
def toNearestInt(x):
return int(x+0.5)
but it doesn't work for negative integers. 但不适用于负整数。
>>> toNearestInt(3)
3
>>> toNearestInt(3.0)
3
>>> toNearestInt(3.49)
3
>>> toNearestInt(3.50)
4
>>> toNearestInt(-3)
-2
How can I fix it? 我该如何解决?
Python already has a builtin for this (more or less). 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
Of course, you might want to wrap that in a call to int
... 当然,您可能希望将其包装在对
int
的调用中...
def toNearestInt(x):
return int(round(x, 0))
You could keep your initial approach here and just check to see if the input is negative and add -0.5 in that case. 您可以在这里保留最初的方法,仅检查输入是否为负数,然后添加-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.