This question already has an answer here:
这个问题在这里已有答案:
- ruby: converting from float to integer in ruby produces strange results 3 answers
ruby:在ruby中从float转换为integer会产生奇怪的结果3个答案
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
当我添加0.1 + 0.2时,我得到0.30000000000000004但是当我在ruby 1.8.7中添加相同的数字时,我得到了正确答案0.3。我通过舍入得到0.3,但我只想通过加0.1和0.2得到红宝石1.9.2上的0.3
2 个解决方案
#1
11
You need bigdecimal for this to make work.
你需要bigdecimal来做这项工作。
(BigDecimal('0.1') + BigDecimal("0.2")).to_f
See below link:
见以下链接:
#2
7
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.
浮点数是非常棘手的野兽。
#1
11
You need bigdecimal for this to make work.
你需要bigdecimal来做这项工作。
(BigDecimal('0.1') + BigDecimal("0.2")).to_f
See below link:
见以下链接:
#2
7
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.
浮点数是非常棘手的野兽。