Python 中的数字四舍五入到 5 万

Round numbers to 50 thousands in Python

如何将数字四舍五入到最接近的 5 万?

我想将此 542756 舍入为 550000,或将此 521405 舍入为 500000。考虑到要四舍五入的数字是一个变量x.

我试过这个:

import math

def roundup(x):
    return int(math.ceil(x / 50000.0)) * 50000

但它只是四舍五入,我需要向上或向下舍入。

我也试过这个:

round(float(x), -5)

但是这一轮要精确到十万。

我想有一个简单的解决方案,但找不到任何东西。

您可以使用:

def round_nearest(x,num=50000):
    return int(round(float(x)/num)*num)

如果您处理大数,您也可以避免转换为浮点数。在这种情况下,您可以使用:

def round_nearest<b>_large</b>(x,num=50000):
    return ((x+num//2)//num)*num

您可以使用两个参数来调用它以四舍五入到最接近的 num,或者没有将四舍五入到最接近的 50000。如果您不希望结果是这样,您可以省略 int(..) int(..) 本身(例如,如果你也想在 0.5 上四舍五入)。在那种情况下,我们可以定义:

def round_nearest<b>_float</b>(x,num=50000):
    return round(float(x)/num)*num

这会产生:

>>> round_nearest(542756)
550000
>>> round_nearest(521405)
500000

或者如果您希望另一个数字四舍五入为:

>>> round_nearest(542756,1000)
543000
>>> round_nearest(542756,200000)
600000
def round_nearest(x, multiple):
    return math.floor(float(x) / multiple + 0.5) * multiple

>>> round_nearest(542756, 50000)
550000
>>> round_nearest(521405, 50000)
500000

divmod 在这种情况下可以成为你的朋友

def roundmynumber(x):
    y,z = divmod(x,50000)
    if z >25000: y +=1
    return int(50000*y)

>>> roundmynumber(83000)
100000
>>> roundmynumber(13000)
0
>>> roundmynumber(52000)
50000
>>> roundmynumber(152000)
150000
>>> roundmynumber(172000)
150000
>>> roundmynumber(152000.045)
150000
>>> roundmynumber(-152000.045)
-150000