Search code examples
ruby-on-railsrubybigdecimal

Comparing bigdecimal output


A SQL query is outputting a bigdecimal output that I expect to be 144.50, and the actual value is coming as #<BigDecimal:7fbe367ed118,'0.1445E3',18(18)>

I tried the following to compare the two:

assert_equal BigDecimal('144.50'), actual_value

but this fails with:

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

Looks like the failure is because of the actual and expected values being different objects.

Is this the right way to compare big decimal objects in Ruby?


Solution

  • Your assertion is saying "does this object equal this other object". It appears you want to compare values.

    You can do that like so:

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

    That would make your test look something like:

    assert_equal 144.50, actual_value
    

    where actual_value is coming from the database.