Python 将整数四舍五入到最接近的 10
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3348825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round integers to the nearest 10
提问by tablo_an
I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats.
我正在尝试在 python 中舍入整数。我查看了内置的 round() 函数,但似乎 rounds 是浮动的。
My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc.
我的目标是将整数四舍五入到最接近的 10 倍数。即:5-> 10、4-> 0、95->100 等。
5 and higher should round up, 4 and lower should round down.
5 和更高应该四舍五入,4 和更低应该四舍五入。
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?
这是实现我想要实现的目标的最佳方式吗?有没有内置函数可以做到这一点?另外,如果这是最好的方法,我在测试中遗漏的代码有什么问题吗?
采纳答案by data
Actually, you could still use the round function:
实际上,您仍然可以使用 round 函数:
>>> print round(1123.456789, -1)
1120.0
This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.
这将四舍五入到最接近的 10 倍数。到 100 将是 -2 作为第二个参数,依此类推。
回答by cobbal
Slightly simpler:
稍微简单一点:
def round_int(x):
return 10 * ((x + 5) // 10)
回答by data
if you want the algebric form and still use round for it it's hard to get simpler than:
如果您想要代数形式并仍然使用 round ,那么很难变得比以下更简单:
interval = 5
n = 4
print(round(n/interval))*interval
回答by Mark Tolonen
round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:
round() 可以采用整数和负数作为位置,四舍五入到小数点的左边。返回值仍然是一个浮点数,但一个简单的转换修复了:
>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000
回答by dawg
This function will round either be order of magnitude (right to left) or by digits the same way that format treats floating point decimal places (left to right:
此函数将按数量级(从右到左)或按数字舍入,格式与处理浮点小数位的方式相同(从左到右:
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)))
Prints
印刷
5555555 rounded to 2 places:
5555600 right to left
5600000 left to right
You can also use Decimal class:
您还可以使用 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
On Python 3 you can reliably use round with negative places and get a rounded integer:
在 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)
On Python 2, round will fail to return a proper rounder integer on larger numbers because round always returns a float:
在 Python 2 上,round 将无法在较大的数字上返回适当的舍入整数,因为 round 总是返回一个浮点数:
>>> round(2**34, -5)
17179900000.0 # OK
>>> round(2**64, -5)
1.84467440737096e+19 # wrong
The other 2 functions work on Python 2 and 3
其他 2 个函数适用于 Python 2 和 3
回答by Evgeni Sergeev
About the round(..)function returning a float
关于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.)
该浮点数(Python 中的双精度)始终是整数的完美表示,只要它在 [-2 53..2 53]范围内。(学究们注意:它不是双打中的补码,因此范围关于零对称。)
See the discussion herefor details.
回答by The Monster
I wanted to do the same thing, but with 5 instead of 10, and came up with a simple function. Hope it's useful:
我想做同样的事情,但是用 5 而不是 10,并想出了一个简单的函数。希望有用:
def roundToFive(num):
remaining = num % 5
if remaining in range(0, 3):
return num - remaining
return num + (5 - remaining)

