如何防止Ruby钱浮点错误

我正在使用带有money-rails gem的Rails来处理钱列。

有没有办法防止浮点错误发生? (即使是黑客也会这样做,我只是想确保没有这样的错误呈现给最终用户)

Rspec示例案例:

it "correctly manipulates simple money calculations" do # Money.infinite_precision = false or true i've tried both start_val = Money.new("1000", "EUR") expect(start_val / 30 * 30).to eq start_val end 

结果

 Failure/Error: expect(start_val / 30 * 30).to eq start_val expected: # got: # (compared using ==) Diff: @@ -1,2 +1,2 @@ -# +# 

你应该使用小数金作为金额。 例如,请参见http://ruby-doc.org/stdlib-2.1.1/libdoc/bigdecimal/rdoc/BigDecimal.html 。 它具有任意精度算术。

编辑:在你的情况下,你可能应该将你的Rspec改为:

 it "correctly manipulates simple money calculations" do # Money.infinite_precision = false or true i've tried both start_val = Money.new("1000", "EUR") thirty = BigDecimal.new("30") expect(start_val / thirty * thirty).to eq start_val end 

EDIT2:在这种情况下,1000/30不能表示为有限的十进制数。 您必须使用Rational类或进行舍入。 示例代码:

 it "correctly manipulates simple money calculations" do # Money.infinite_precision = false or true i've tried both start_val = Money.new("1000", "EUR") expect(start_val.amount.to_r / 30.to_r * 30.to_r).to eq start_val.amount.to_r end