2012-01-05 45 views
2
ruby-1.8.7 > 1.55.round(1) 
=> 1.6 
ruby-1.8.7 > 1.555.round(2) 
=> 1.56 
ruby-1.8.7 > 1.155.round(2) 
=> 1.16 
ruby-1.8.7 > 10.156.round(2) 
=> 10.16 
ruby-1.8.7 > 10.155.round(2) 
=> 10.15 
ruby-1.8.7 > 10.165.round(2) 
=> 10.16 

是什麼給出的?我錯過了什麼嗎?在紅寶石中浮動圓形錯誤?

EDIT

ruby-1.9.2 > 10.155.round(2) 
=> 10.15 
ruby-1.9.2 > 10.165.round(2) 
=> 10.16 
+1

可能與:http://stackoverflow.com/questions/1950541/consistent-rounding-of-floating-points -in-ruby – Thilo 2012-01-05 12:18:39

+0

謝謝,這至少爲我提供了一種解決方法。也許它確實與浮點不精確有關... – tbk 2012-01-05 12:29:01

+0

也相關:http://stackoverflow.com/questions/4055618/ruby-floating-point-errors – 2012-01-05 13:27:48

回答

4

浮點值不準確。您的10.165在紙上/屏幕上顯示爲10.165,但在內存中它表示爲與10.165非常接近的東西......是向上還是向下傾斜是錯誤發生的方向。

如果您需要精確處理分數,您可以將它們表示爲BigDecimal(帶小數點/精度表示法),或者表示爲Rational(帶分數/分母表示法)。