2013-07-15 19 views
1

我需要採用0.405這樣的數字,並將其舍入到0.40,同時舍入爲0.412到0.42。有沒有內置的功能來做到這一點?向上浮動至最接近的2/100

+1

請問'圓(X /(0.02))* 0.02'工作? (你必須檢查你想如何處理邊界案例,因爲2/100不是二元的。) – DSM

+0

似乎可行,謝謝,如果你想指出它,你應該寫出來。 – deltap

回答

4

通用的解決方案,這允許舍入到一個任意分辨率(當然,除了當然爲零,但零的分辨率變得毫無意義的(a))。對於您的情況,您只需要提供0.02作爲分辨率,但其他值也是可能的,如測試用例中所示。

# This is the function you want. 

def roundPartial (value, resolution): 
    return round (value/resolution) * resolution 

# All these are just test cases, the first two being your own test data. 

print "Rounding to fiftieths" 
print roundPartial (0.405, 0.02) 
print roundPartial (0.412, 0.02) 

print "Rounding to quarters" 
print roundPartial (1.38, 0.25) 
print roundPartial (1.12, 0.25) 
print roundPartial (9.24, 0.25) 
print roundPartial (7.76, 0.25) 

print "Rounding to hundreds" 
print roundPartial (987654321, 100) 

此輸出:

Rounding to fiftieths 
0.4 
0.42 
Rounding to quarters 
1.5 
1.0 
9.25 
7.75 
Rounding to hundreds 
987654300.0 

(一)如果您有需要你來處理這種可能性的具體人格障礙,要知道,你以後最接近的數字是您想要的分辨率的倍數。由於最近數N(用於任何N)是0的倍數始終爲0,可以按如下修改功能:

def roundPartial (value, resolution): 
    if resolution == 0: 
     return 0 
    return round (value/resolution) * resolution 

或者,你可以簡單地保證自己不通過零分辨率:-)

+0

我認爲處理零分辨率的更好方法就是返回輸入。如果您在分辨率趨於零的極限內想到它,則輸出趨向於輸入。 –

+0

太糟糕了,您還沒有將OP指向您以前的[問題](http://stackoverflow.com/q/8118982/12892)和[答案](http://stackoverflow.com/a/8119014/12892) 。 –

0

小修復到以前的解決方案:

def roundPartial (value, resolution): 
    return round (float(value)/resolution) * resolution 

早些時候

roundPartial(19, 10) = 10.0 

隨着修復

roundPartial(19, 10) = 20.0