Ruby thinks (19.99 * 100).to_i = 1998

March 26th, 2009 By: Daniel
>> (19.99 * 100).to_i
=> 1998
>> (9.99 * 100).to_i
=> 999

Someone please tell me what’s up with that!

In the meantime:

>> (19.99 * 100).to_s.to_i
=> 1999

4 Responses to “Ruby thinks (19.99 * 100).to_i = 1998”

  1. Leo Says:

    That is crazy! I am not going to use ruby to do math.

  2. Wes Bangerter Says:

    “This behavior is not specific to Ruby. The reason Ruby behaves like this is that it adheres
    to the IEEE standard for floating point numbers, which is common to most programming languages.”
    From http://www.ruby-forum.com/topic/178503

    You can read more about it at:
    http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

    Or a lot more about it at:
    http://docs.sun.com/source/806-3568/ncg_goldberg.html

  3. Marnen Laibow-Koser Says:

    Wes: I’m not surprised that this is an IEEE float issue.

    Leo: Wrong conclusion. The right conclusion: don’t use *IEEE floats* to do math. Ruby has a BigDecimal library that completely gets around this problem by not using IEEE floats. Use it for math.

  4. Wes Bangerter Says:

    Just to verify what Marnen wrote, using a BigDecimal works with the example Daniel posted.

    >> require ‘bigdecimal’
    >> (BigDecimal.new(’19.99′) * 100).to_i
    => 1999

Leave a Reply