ruby to_f bug或乘法运算符bug?

NoT*_*iTo 2 ruby rounding multiplication

嗨,我刚遇到一个问题,其中ruby的to_f功能给了我不一致的结果.

ruby-1.9.2-head :026 > 8.45.to_f * 100
 => 844.9999999999999 

ruby-1.9.2-head :027 > 4.45.to_f * 100
 => 445.0 


ruby-1.9.2-head :028 > 4.35.to_f * 100
 => 434.99999999999994 
Run Code Online (Sandbox Code Playgroud)

我的解决方法是简单地以这种方式舍入结果

ruby-1.9.2-head :029 > (4.35.to_f * 100).round
 => 435 
Run Code Online (Sandbox Code Playgroud)

经过更多的游戏后,我意识到问题可能出在乘法运算符上 * 100

jer*_*jer 5

欢迎来到浮点漂移.这是一个很好理解的问题,你应该阅读,所以你至少要自己理解.例如,看看下面的文章: