开发者

Addition error with ruby-1.9.2 [duplicate]

This question already has answers here: 开发者_运维问答 ruby: converting from float to integer in ruby produces strange results (3 answers) Closed 4 years ago.

When I add 0.1+0.2 I am getting 0.30000000000000004 but when I add the same number in ruby 1.8.7 I am getting the correct answer 0.3. I get 0.3 by rounding but I just want to get 0.3 on ruby 1.9.2 by adding 0.1 and 0.2


You need bigdecimal for this to make work.

(BigDecimal('0.1') + BigDecimal("0.2")).to_f

See below link:

http://redmine.ruby-lang.org/issues/4394


Your old ruby lied to you:

$ ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [x86_64-linux]
$ irb
irb(main):001:0> printf("%40.40f\n", 0.1 + 0.2)
0.3000000000000000444089209850062616169453
=> nil

Floating point numbers are very tricky beasts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜