2017-03-31 19 views
1

如何將數字四捨五入到最接近的5萬個?Python中的數字爲5萬個數字

我想將此542756四捨五入至此550000,或將此521405四捨五入至此500000。考慮到要舍入的數字是一個變量x

我嘗試這樣做:

import math 

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

但它只是圓了,我需要兩個圓向上或向下。

我也試過這樣:

round(float(x), -5) 

但這四捨五入到最接近十萬。

我想有一個簡單的解決方案,但找不到任何東西。

+4

整數或浮點數輸入?應該如何處理一半情況(例如'525000')?什麼是負面投入? –

+0

可能重複[舍入到最近的500,Python](http://stackoverflow.com/questions/9810391/round-to-the-nearest-500-python) –

回答

6

您可以使用:

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 
+0

只是一個評論,如果它是整數輸入,整數-out,那麼使用純整數操作可能會更好,以避免使用浮點數而導致精度損失。例如,'round_nearest(100000000000000925000)'給出'100000000000000901120',這是不準確的並且以錯誤的方式舍入。 (但OP似乎並不想告訴我們需求是什麼,所以它可能沒有關係。) –

+0

@MarkDickinson:更新,更好? –

+0

謝謝!我還不清楚中途情況會發生什麼。 –

1
def round_nearest(x, multiple): 
    return math.floor(float(x)/multiple + 0.5) * multiple 

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

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 
+0

在這裏使用'24999.99'不是一個好主意。如果你想比較'25000',比較'25000'。 –

+0

接受了您的建議! –

相關問題