Why does Ruby refuse equality on 2 floats that look the same?

I have a calculation that generates what Float 22.23 seems to be, and the letter 22.23:

some_object.total => 22.23
some_object.total.class => Float

22.23 => 22.23
22.23.class => Float

But for some reason, the following is not true:

some_object.total == 22.23 ? true : false

Strange, right?

Is there some kind of precision mechanism in use that may not be completely transparent through some_object.total?

+5
source share
3 answers

. , 0,9 0,9, 0,9, , . , , - , . , 0.3 * 3 == 0.9 false. , - , - . ., , Haskell.

, , . , :

def float_equal(a, b)
  if a + 0.00001 > b and a - 0.00001 < b
    true
  else
    false
  end
end

BigDecimal Ruby .

, assert_in_delta:

def test_some_object_total_is_calculated_correctly
  assert_in_delta 22.23, some_object.total, 0.01
end
+9

Float#to_s Float#inspect . "%.30f" % some_object.total, , 22.23.

+6

something else happens here. it's from 1.8.7 irb

irb(main):001:0> class Test
irb(main):002:1> attr_accessor :thing
irb(main):003:1> end
=> nil
irb(main):004:0> t = Test.new
=> #<Test:0x480ab78>
irb(main):005:0> t.thing = 22.5
=> 22.5
irb(main):006:0> t.thing == 22.5
=> true
+1
source

All Articles