ruby: converting from float to integer in ruby produces strange results

后端 未结 3 2094
闹比i
闹比i 2020-12-10 22:42
ree-1.8.7-2010.02 :003 > (10015.8*100.0).to_i
 => 1001579 
ree-1.8.7-2010.02 :004 > 10015.8*100.0
 => 1001580.0 
ree-1.8.7-2010.02 :005 > 1001580.0.to         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 23:27

    http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

    >> sprintf("%.16f", 10015.8*100.0)
    => "1001579.9999999999000000"
    

    And Float#to_i truncates this to 1001579.

提交回复
热议问题