比较 bigdecimal 输出

Comparing bigdecimal output

一个 SQL 查询正在输出一个我期望为 144.50 的 bigdecimal 输出,而实际值是 #<BigDecimal:7fbe367ed118,'0.1445E3',18(18)>

我尝试了以下方法来比较两者:

assert_equal BigDecimal('144.50'), actual_value

但这失败了:

--- expected
+++ actual
@@ -1 +1 @@
-#<BigDecimal:7fbe367ed938,'0.1445E3',18(18)>
+#<BigDecimal:7fbe367ed118,'0.1445E3',18(18)>

看起来失败是因为实际值和预期值是不同的对象。

这是在 Ruby 中比较大十进制对象的正确方法吗?

您的断言是 "does this object equal this other object"。您似乎想要比较值。

你可以这样做:

[4] pry(main)> BigDecimal('144.50') == 144.50                                             
=> true

这将使您的测试看起来像:

assert_equal 144.50, actual_value

其中 actual_value 来自数据库。