【问题标题】:Round integers to the nearest 10将整数四舍五入到最接近的 10
【发布时间】:2011-03-21 21:36:55
【问题描述】:

我正在尝试在 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

这是实现我想要实现的目标的最佳方式吗?有没有内置函数可以做到这一点?另外,如果这是最好的方法,那我在测试中遗漏的代码有什么问题吗?

【问题讨论】:

  • 您注意到 cobbal 的回答中的 // 了吗?最好在这里使用,因为它与 Python3+ 前向兼容,/ 现在可以返回一个浮点数
  • 哦,我还以为是错字。如果我知道我只会使用 python2.6 可以吗?
  • 是的。我目前可用的最低版本是 2.3.4,整数除法无需from __future__ import division 语句即可使用。我认为它是在__future__ 2.2 中首次引入的,但我可能弄错了。
  • @Nathan Ernst,导入相反。 // 早就支持了,所以使用起来非常安全。 The from __future__ import division 更改 / 的行为以匹配 Python3

标签: python


【解决方案1】:

其实还是可以用round函数的:

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

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

【讨论】:

  • 这真的很有帮助
  • 这很棒。有没有类似的简单的四舍五入技巧?
【解决方案2】:

round() 可以采用整数和负数来表示位置,它们在小数点的左边四舍五入。返回值仍然是一个浮点数,但一个简单的强制转换解决了这个问题:

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

【讨论】:

    【解决方案3】:

    稍微简单一点:

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

    【讨论】:

    • 哈哈按照 x in (-5, -15, -25, ...) 的要求四舍五入,这不是一般投注者所期望的
    • 平均下注者使用负数。有道理
    【解决方案4】:

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

    浮点数(Python 中的双精度)始终是整数的完美表示,只要它在 [-253..253 范围内]。 (学究们注意:双数中不是二进制补码,所以范围关于零对称。)

    详情请参阅discussion here

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        【解决方案6】:

        如果您想要代数形式并且仍然使用圆形,那么很难比:

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

        【讨论】:

          【解决方案7】:

          此函数将按数量级(从右到左)或按位数四舍五入,与格式处理浮点小数位的方式相同(从左到右:

          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 上,您可以可靠地使用带有负数的 round 并得到一个四舍五入的整数:

          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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-07-26
            • 2013-06-13
            • 1970-01-01
            • 2013-08-31
            • 2017-05-03
            • 1970-01-01
            相关资源
            最近更新 更多