2010-11-09 111 views
4

我有一個數字值,如30.6355代表金錢,如何舍入到小數點後兩位?我有一個數值,如30.6355,代表金錢,如何四捨五入到小數點後兩位?

+2

你賣的汽油?你爲什麼要把錢存到第5個小數點? – 2010-11-09 04:22:25

+1

可能的重複[舍入到最接近的0.05的ruby整數](http://stackoverflow.com/questions/1346257/round-a-ruby-integer-up-to-the-nearest-0-05) - 問題說0.05,但相同的技術適用於任何單位,如0.01 – 2010-11-09 04:24:18

+2

哦,浮動金錢......再次......是0.0055累積浮動誤差? ))) – Nakilon 2010-11-09 04:27:42

回答

13

紅寶石1.8:

class Numeric 
    def round_to(places) 
     power = 10.0**places 
     (self * power).round/power 
    end 
end 

(30.6355).round_to(2) 

紅寶石1.9:

(30.6355).round(2) 

在1.9,round能輪到數字的指定數量。

20

與貨幣打交道時,你不應使用doublefloat類型:他倆都太多小數和偶爾的舍入誤差。資金可能會通過這些漏洞陷入困境,並且在發生錯誤後很難追查這些錯誤。

當處理金錢時,使用固定的十進制類型。在Ruby(和Java)中,使用BigDecimal。

+8

實際上,最大的問題是它們根本沒有任何小數位*,它們有*二進制*位置。 – 2010-11-09 05:09:15

+0

@Jörg,是對的。請參閱http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems以獲取解釋。 – lucasrizoli 2010-11-09 05:59:05

+0

'寶石安裝錢'。 http://money.rubyforge.org/ – 2010-11-09 09:18:01

0

這將圍繞一些有用的案例 - 寫得不好,但它的作品!隨意編輯。

def round(numberString) 
numberString = numberString.to_s 
decimalLocation = numberString.index(".") 
numbersAfterDecimal = numberString.slice(decimalLocation+1,numberString.length-1) 
numbersBeforeAndIncludingDeciaml = numberString.slice(0,decimalLocation+1) 

if numbersAfterDecimal.length <= 2 
    return numberString.to_f 
end 

thingArray = numberString.split("") 
thingArray.pop 

prior = numbersAfterDecimal[-1].to_i 
idx = numbersAfterDecimal.length-2 

thingArray.reverse_each do |numStr| 
    if prior >= 5 
     numbersAfterDecimal[idx] = (numStr.to_i + 1).to_s unless (idx == 1 && numStr.to_i == 9) 
     prior = (numStr.to_i + 1) 
    else 
     prior = numStr.to_i 
    end 
    break if (idx == 1) 
    idx -= 1 
end 

resp = numbersBeforeAndIncludingDeciaml + numbersAfterDecimal[0..1] 
resp.to_f 
end 

round(18.00) == 18.0

round(18.99) == 18.99

round(17.9555555555) == 17.96

round(17.944444444445) == 17.95

round(15.545) == 15.55

round(15.55) == 15.55

round(15.555) == 15.56

round(1.18) == 1.18

round(1.189) == 1.19

相關問題