此函数将按大小顺序(从右至左)舍入或按数字舍入,这与格式处理浮点小数位(从左至右)的方式相同:
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
您还可以使用Decimal类:
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
在Python 3上,您可以可靠地使用带有负数的舍入并获得舍入的整数:
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)
在Python 2上,由于round始终返回浮点数,因此round不能对较大的数字返回适当的舍入整数。
>>> round(2**34, -5)
17179900000.0
>>> round(2**64, -5)
1.84467440737096e+19
其他2个功能可在Python 2和3上使用
//cobbal的回答?这是更好,因为它是与Python3 +向前兼容在这里用/现在可以返回一个浮点数