any body can help me ?? why is this happen??

Hii All

I use ruby 1.8.7 I run irb and type:

a = (0.29 * 100).to_i

the result is 28

why???

could u explain to me… Please???

THank you

Scary!

irb(main):019:0> (0.57 * 100).to_i => 56 irb(main):020:0> (0.58 * 100).to_i => 57

This is totally out of my understanding.... Will look into core... seems like some bug...

(0.29*100).to_s.to_i will return what you expect.

Nm... this explains it:

http://rubypond.com/blog/when-ruby-floating-just-isn-t-good-enough

See this may be u get some idea… http://rubypond.com/blog/when-ruby-floating-just-isn-t-good-enough

-Shyam

Quoting anton effendi <wuyouduan@gmail.com>:

Hii All

I use ruby 1.8.7 I run irb and type:

a = (0.29 * 100).to_i

the result is 28

Here's why:

irb(main):008:0> '%0.16f' % (0.29 * 100) => "28.9999999999999964"

Most decimal fractions cannot be represented exactly in binary. If you need them to behave in certain ways, e.g. using real numbers to represent US dollars and cents, take care and learn to use the following functions as needed.

irb(main):002:0> (0.29 * 100).to_i => 28 irb(main):003:0> (0.29 * 100).round => 29 irb(main):004:0> (0.29 * 100).floor => 28 irb(main):005:0> (0.29 * 100).ceil => 29 irb(main):009:0> (-0.29 * 100) => -29.0 irb(main):010:0> (-0.29 * 100).to_i => -28 irb(main):011:0> (-0.29 * 100).floor => -29 irb(main):012:0> (-0.29 * 100).round => -29 irb(main):013:0> (-0.29 * 100).ceil => -28

IIRC, .to_i rounds towards zero, .floor rounds down, .ceil rounds up, and .round adds 1/2 and rounds towards zero.

HTH,   Jeffrey

P.S. if you are in the financial field, the SEC has rules on how to do arithmetic in US dollars and cents.

Thank you all I found why that happen…