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
–
Senior Rails Developer
Anton Effendi - Wu You Duan
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
–
Senior Rails Developer
Anton Effendi - Wu You Duan
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.
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.
See this may be u get some idea…
http://rubypond.com/blog/when-ruby-floating-just-isn-t-good-enough
-Shyam
Thank you all
I found why that happen…
On Wed, Mar 31, 2010 at 11:39 PM, Jeffrey L. Taylor
[email protected]wrote:
Here’s why:
irb(main):002:0> (0.29 * 100).to_i
=> -28To unsubscribe from this group, send email to
[email protected][email protected]
.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.
–
Senior Rails Developer
Anton Effendi - Wu You Duan
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs