Round integers to the nearest 10

I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats.

My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc.

5 and higher should round up, 4 and lower should round down.

This is the code I have that does this:

def round_int(x):
last_dig = int(str(x)[-1])
if last_dig >= 5:
x += 10
return (x/10) * 10

Is this the best way to achieve what I want to achieve? Is there a built-in function that does this? Additionally, if this is the best way, is there anything wrong with the code that I missed in testing?

119128 次浏览

简单一点:

def round_int(x):
return 10 * ((x + 5) // 10)

实际上,您仍然可以使用 round 函数:

>>> print round(1123.456789, -1)
1120.0

这将四舍五入到最接近的倍数10。到100就是 -2作为第二个参数,以此类推。

如果你想要代数形式,并且仍然使用四舍五入,那么很难得到比下面更简单的形式:

interval = 5
n = 4
print(round(n/interval))*interval

Round ()可以取整数和负数作为小数点左边的四舍五入位数。返回值仍然是一个 float,但是通过一个简单的强制转换就可以解决这个问题:

>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000

这个函数的四舍五入数量级(从右到左)或者按照格式对待浮点小数位(从左到右:

def intround(n, p):
''' rounds an intger. if "p"<0, p is a exponent of 10; if p>0, left to right digits '''
if p==0: return n
if p>0:
ln=len(str(n))
p=p-ln+1 if n<0 else p-ln
return (n + 5 * 10**(-p-1)) // 10**-p * 10**-p


>>> tgt=5555555
>>> d=2
>>> print('\t{} rounded to {} places:\n\t{} right to left \n\t{} left to right'.format(
tgt,d,intround(tgt,-d), intround(tgt,d)))

指纹

5555555 rounded to 2 places:
5555600 right to left
5600000 left to right

You can also use Decimal class:

import decimal
import sys


def ri(i, prec=6):
ic=long if sys.version_info.major<3 else int
with decimal.localcontext() as lct:
if prec>0:
lct.prec=prec
else:
lct.prec=len(str(decimal.Decimal(i)))+prec
n=ic(decimal.Decimal(i)+decimal.Decimal('0'))
return n

在 Python3中,你可以可靠地使用圆和负的位置,得到一个四舍五入的整数:

def intround2(n, p):
''' will fail with larger floating point numbers on Py2 and require a cast to an int '''
if p>0:
return round(n, p-len(str(n))+1)
else:
return round(n, p)

在 Python2中,round 将无法在较大的数字上返回一个合适的整数,因为 round 总是返回一个 float:

>>> round(2**34, -5)
17179900000.0                     # OK
>>> round(2**64, -5)
1.84467440737096e+19              # wrong

其他2个函数用于 Python2和3

关于返回浮点数的 round(..)函数

That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

有关详细信息,请参阅 讨论

我想做同样的事情,但是用5代替了10,并且提出了一个简单的函数。希望它有用:

def roundToFive(num):
remaining = num % 5
if remaining in range(0, 3):
return num - remaining
return num + (5 - remaining)