Quoting anton effendi <[email protected]>:
> 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.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to