将整数舍入到最接近的10


72

我正在尝试在python中舍入整数。我看了内置的round()函数,但似乎舍入浮动了。

我的目标是将整数四舍五入到最接近的10的倍数。例如:5-> 10、4-> 0、95-> 100,等等。

5和更高的值应四舍五入,4和更低的值应四舍五入。

这是我这样做的代码:

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

这是实现我想要实现的最好方法吗?有内置的功能吗?另外,如果这是最好的方法,那么我在测试中遗漏的代码是否有问题?


1
您是否注意到//cobbal的回答?这是更好,因为它是与Python3 +向前兼容在这里用/现在可以返回一个浮点数
约翰·拉ROOY

哦,我认为这是一个错字。如果我知道我只会使用python2.6,可以吗?
tablo_an 2010年

是。我目前可以使用的最低版本是2.3.4,并且整数除法无需from __future__ import division声明即可。我认为它是在2.2中首次引入的__future__,但我可能会误解。
内森·恩斯特

@Nathan Ernst,导入工作相反。//从很早以前就受到支持,因此使用非常安全。The from __future__ import division更改的行为/以匹配Python3
John La Rooy 2010年

Answers:


128

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

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

这将舍入到最接近的10的倍数。第二个参数为100,-2为-,依此类推。


这真的很有帮助
Sreekiran

28

round()可以为小数点左边的整数取整数和负数。返回值仍然是浮点数,但是通过简单的强制转换可以修复:

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

8

稍微简单一点:

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

1
哈哈根据x in(-5,-15,-25,...)的要求四舍五入,这不是平均下注者期望发生的情况
John Machin

平均投注者使用负钱。很有道理
jsky 2015年

3

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

浮点数(Python中的双精度)始终是整数的完美表示,只要它在[-2 53 ..2 53 ]范围内即可。(步行者要注意:不是双的补码,所以范围是对称于零的。)

有关详细信息,请参见此处讨论


3

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

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

1

如果您想使用代数形式并且仍然使用round,那么很难简单地做到以下几点:

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

1

此函数将按大小顺序(从右至左)舍入或按数字舍入,这与格式处理浮点小数位(从左至右)的方式相同:

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                     # OK
>>> round(2**64, -5)
1.84467440737096e+19              # wrong 

其他2个功能可在Python 2和3上使用

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.