十進制 二進制
0.1 0.0001 1001 1001 1001 ...
0.2 0.0011 0011 0011 0011 ...
0.3 0.0100 1100 1100 1100 ...
0.4 0.0110 0110 0110 0110 ...
0.5 0.1
0.6 0.1001 1001 1001 1001 ...
所以比如 1.1 ,其程序實際上無法真正的表示 ‘1.1',而只能做到一定程度上的準確,這是無法避免的精度丟失:
1.09999999999999999
在JavaScript中問題還要復雜些,這里只給一些在Chrome中測試數據:
輸入 輸出
1.0-0.9 == 0.1 False
1.0-0.8 == 0.2 False
1.0-0.7 == 0.3 False
1.0-0.6 == 0.4 True
1.0-0.5 == 0.5 True
1.0-0.4 == 0.6 True
1.0-0.3 == 0.7 True
1.0-0.2 == 0.8 True
1.0-0.1 == 0.9 True
解決
那如何來避免這類 1.0-0.9 != 0.1 的非bug型問題發生呢?下面給出一種目前用的比較多的解決方案, 在判斷浮點運算結果前對計算結果進行精度縮小,因為在精度縮小的過程總會自動四舍五入:
isEqual(1.0-0.7, 0.3); // return true
// 原生擴展方式,更喜歡面向對象的風格
Number.prototype.isEqual = function(number, digits){
digits = digits == undefined? 10: digits; // 默認精度為10
return this.toFixed(digits) === number.toFixed(digits);
}
(1.0-0.7).isEqual(0.3); // return true
新聞熱點
疑難解答