[rspec-users] Why can not a BigDecimal be compared to a Float via "==". How should I handle this???
dchelimsky at gmail.com
Sun Jan 11 09:21:07 EST 2009
On Sun, Jan 11, 2009 at 4:05 AM, Greg Hauptmann
<greg.hauptmann.ruby at gmail.com> wrote:
> I've gone with the following
> ai.amount.should == BigDecimal('-323.03')
> However I'm still a bit surprised that Ruby itself does allow a good "=="
> test between a Float and a BigDecimal. Perhaps there's a reason that I'm
Very telling is this:
>> require 'bigdecimal'
>> BigDecimal.new(3333333.0) == 3333333.0
TypeError: can't convert Float into String
from (irb):4:in `new'
As for why, I think you'll get some good insights if you post the
ruby-lang mailing list, but I can take shot.
BigDecimal has explicit precision. Float does not. Imagine the
developer at the bank explaining that the thousands of dollars
discrepancy last year was due to an average miscalculation of 0.00005
per transaction because sometimes the code used BigDecimal, and
sometimes it used Float.
Personally, I think this seeming annoyance is actually a good thing.
> On Sun, Jan 11, 2009 at 7:23 PM, Mark Wilden <mark at mwilden.com> wrote:
>> On Sun, Jan 11, 2009 at 12:17 AM, Greg Hauptmann
>> <greg.hauptmann.ruby at gmail.com> wrote:
>>> Any suggestions on how to write an rspec expectation for equality when
>>> you get a BigDecimal back. I see that "big_decimal_variable.should ==
>>> 123.23" doesn't work as the ruby BigDecimal comparison (via ==) to the same
>>> Float value gives false (not true as you'd expect).
>> How about bd.to_s.should == 123.23.to_s ?
More information about the rspec-users