繁体   English   中英

在Python中将数字舍入到50,000

[英]Round numbers to 50 thousands in Python

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

我想将这个542756542756到这个550000 ,或者将这个521405521405到这个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_large(x,num=50000):
    return ((x+num//2)//num)*num

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

def round_nearest_float(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM