我有一個數字值,如30.6355代表金錢,如何舍入到小數點後兩位?我有一個數值,如30.6355,代表金錢,如何四捨五入到小數點後兩位?
回答
紅寶石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能輪到數字的指定數量。
與貨幣打交道時,你不應使用double
或float
類型:他倆都太多小數和偶爾的舍入誤差。資金可能會通過這些漏洞陷入困境,並且在發生錯誤後很難追查這些錯誤。
當處理金錢時,使用固定的十進制類型。在Ruby(和Java)中,使用BigDecimal。
實際上,最大的問題是它們根本沒有任何小數位*,它們有*二進制*位置。 – 2010-11-09 05:09:15
@Jörg,是對的。請參閱http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems以獲取解釋。 – lucasrizoli 2010-11-09 05:59:05
'寶石安裝錢'。 http://money.rubyforge.org/ – 2010-11-09 09:18:01
這將圍繞一些有用的案例 - 寫得不好,但它的作品!隨意編輯。
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
- 1. 如何四捨五入浮點數。到小數點後兩位?
- 2. 如何將數字四捨五入到小數點後兩位
- 3. 我該如何四捨五入到小數點後一位?
- 4. 不知道如何四捨五入到小數點後兩位
- 5. 如何四捨五入到小數點後兩位PHP
- 6. 爪哇,四捨五入到小數點後兩位數
- 7. 如何四捨五入到小數點後n位C++
- 8. (vb.net)四捨五入到小數點後兩位
- 9. 如何讓這個輸出四捨五入到小數點後兩位?
- 10. 如何將MVC 4中的值四捨五入爲小數點後兩位。
- 11. 沒有四捨五入到五位數
- 12. 四捨五入至小數點後兩位
- 13. 浮點值四捨五入到一個值小數
- 14. '正確'四捨五入到Python,到小數點後三位
- 15. 如何將小數點四捨五入到上限值
- 16. 儘管四捨五入到小數點後兩位,只有一位小數點輸出
- 17. JavaScript四捨五入到小數點後第二位0
- 18. 四捨五入到小數點後第三位在Python
- 19. NSNumberFormatter只四捨五入到小數點後3位
- 20. 如何在Python中將數字四捨五入到小數點後n位
- 21. 如何四捨五入小數點後的數字?
- 22. 如何將浮點列表中的每個項目四捨五入到小數點後兩位?
- 23. 如何在C++中將變量四捨五入到小數點後n位
- 24. MS Access四捨五入SQL小數位
- 25. 我想將一個雙變量四捨五入到兩位小數
- 26. 爲什麼Spreadsheet :: XLSX :: Utility2007的xls2csv四捨五入到小數點後兩位?
- 27. 四捨五入長小數點
- 28. 四捨五入爲最小整數值
- 29. 如何四捨五入數字小數位
- 30. F#四捨五入到小數
你賣的汽油?你爲什麼要把錢存到第5個小數點? – 2010-11-09 04:22:25
可能的重複[舍入到最接近的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
哦,浮動金錢......再次......是0.0055累積浮動誤差? ))) – Nakilon 2010-11-09 04:27:42