2011-11-14 40 views
14

我遇到了以下問題四分之一的時間間隔:Python的 - 通過四捨五入

鑑於各種號碼,如:

10.38

11.12

5.24

9.76

是否存在一個已經存在的「內置」功能米至最接近0.25步驟像例如爲:

10.38 - > 10.50

11.12 - > 11.00

5.24 - > 5.25

9.76 - > 9-75?

或者我可以繼續並將一個執行所需任務的函數一起破解嗎?

在此先感謝和

與問候

回答

24
>>> def my_round(x): 
... return round(x*4)/4 
... 
>>> 
>>> assert my_round(10.38) == 10.50 
>>> assert my_round(11.12) == 11.00 
>>> assert my_round(5.24) == 5.25 
>>> assert my_round(9.76) == 9.75 
>>> 
+0

* head --->辦公桌*確實微不足道 - 我將在5am停止編碼.- 謝謝pulegium和6502 – Daniyal

4

沒有內置,但這樣的功能是微不足道的寫

def roundQuarter(x): 
    return round(x * 4)/4.0 
26

這是一個通用解決方案,允許四捨五入爲任意決議。對於您的具體情況,您只需提供0.25作爲分辨率,但其他值也是可能的,如測試案例中所示。

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

print "Rounding to quarters" 
print roundPartial (10.38, 0.25) 
print roundPartial (11.12, 0.25) 
print roundPartial (5.24, 0.25) 
print roundPartial (9.76, 0.25) 

print "Rounding to tenths" 
print roundPartial (9.74, 0.1) 
print roundPartial (9.75, 0.1) 
print roundPartial (9.76, 0.1) 

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

此輸出:

Rounding to quarters 
10.5 
11.0 
5.25 
9.75 
Rounding to tenths 
9.7 
9.8 
9.8 
Rounding to hundreds 
987654300.0 
+0

一個美麗的通用解決方案。我如何將所有給定的解決方案標記爲「接受答案」? – Daniyal

+3

@Daniyal:你不能。我平常的行爲,如果答案不能按優點排序,那就是把它(連同upvote)給予代表最低的代表,並且也贊成其他代表。在這種情況下,這不是我不幸的:-) – paxdiablo

2

paxdiablo的溶液可以是一點點的改善。

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

所以函數現在是:「數據類型敏感」。