简体   繁体   English

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

[英]Round numbers to 50 thousands in Python

How can I round a number to the nearest up or down 50 thousand? 如何将数字四舍五入到最接近的上下5万?

I want to round this 542756 to this 550000 , or round this 521405 to this 500000 . 我想将这个542756542756到这个550000 ,或者将这个521405521405到这个500000 Considering that the number to be rounded is a variable x . 考虑要舍入的数字是变量x

I tried this: 我试过这个:

import math

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

But it only round up and I need to round both up or down. 但它只是四舍五入,我需要向上或向下四舍五入。

I also tried this: 我也试过这个:

round(float(x), -5)

But this round to the nearest hundred thousand. 但这轮到最近的十万。

I suppose there is a simple solution but couldn't find anything. 我想有一个简单的解决方案但找不到任何东西。

You can use: 您可以使用:

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

You can also avoid converting to floating point if you deal with large numbers . 如果处理大数字,可以避免转换为浮点数。 In that case, you can use: 在这种情况下,您可以使用:

def round_nearest_large(x,num=50000):
    return ((x+num//2)//num)*num

You can call it with two arguments to round to the nearest num , or without will round to the nearest 50000. You can omit the int(..) if you do not want the result to be an int(..) per se (for instance if you want to round on 0.5 as well). 您可以使用两个参数调用它来舍入到最近的num ,或者不会舍入到最接近的50000.如果您不希望结果是int(..)本身,可以省略int(..) (例如,如果你想要在0.5上舍入)。 In that case we can define: 在这种情况下,我们可以定义:

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

This produces: 这会产生:

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

Or if you want another number to round to: 或者,如果您想要另一个数字舍入到:

>>> 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 could be your friend in this case 在这种情况下, 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