几种语言的int((0.1 + 0.7)*10)= 7.怎么预防这个?

cyp*_*her 14 javascript php ruby python internal-representation

最近我遇到了几种语言的bug /功能.我对它是如何引起的有一个非常基本的了解(我想要一些详细的解释),但是当我想到多年来我必须犯下的所有错误时,问题是如何确定" 嘿,这可能会导致一个荒谬的bug,我最好使用任意精度函数 ",其他语言确实有这个bug(和那些没有,为什么).另外,为什么0.1 + 0.7这样做,而0.1 + 0.3没有,还有其他众所周知的例子吗?

PHP

//the first one actually doesn't make any sense to me,
//why 7 after typecast if it's represented internally as 8?
debug_zval_dump((0.1+0.7)*10); //double(8) refcount(1)
debug_zval_dump((int)((0.1+0.7)*10)); //long(7) refcount(1)
debug_zval_dump((float)((0.1+0.7)*10)); //double(8) refcount(1)
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

>>> ((0.1+0.7)*10)
7.9999999999999991
>>> int((0.1+0.7)*10)
7
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

alert((0.1+0.7)*10); //7.999999999999999
alert(parseInt((0.7+0.1)*10)); //7
Run Code Online (Sandbox Code Playgroud)

红宝石:

>> ((0.1+0.7)*10).to_i                                                  
=> 7                                                                    
>>((0.1+0.7)*10)                                                       
=> 7.999999999999999                                                    
Run Code Online (Sandbox Code Playgroud)