gpt4 book ai didi

ruby-on-rails - 如何防止 Ruby money 出现浮点错误

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:19 27 4
gpt4 key购买 nike

我将 Rails 与 money-rails gem 结合使用来处理钱列。

有什么办法可以防止出现 float 错误吗? (即使是 hack 也行,我只是想确保不会向最终用户显示此类错误)

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: #<Money fractional:1000.0 currency:EUR>
got: #<Money fractional:999.99999999999999999 currency:EUR>

(compared using ==)

Diff:
@@ -1,2 +1,2 @@
-#<Money fractional:1000.0 currency:EUR>
+#<Money fractional:999.99999999999999999 currency:EUR>

最佳答案

您应该使用小数表示金额。参见 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

关于ruby-on-rails - 如何防止 Ruby money 出现浮点错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201861/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com