DIV CSS 佈局教程網

為什麼 1.0 - 0.9 不等於 0.1?JavaScript 浮點誤差與解法
編輯:關於JavaScript     

這不是 bug,而是 IEEE 754 double 浮點數表示的必然結果。十進位小數換成二進位後,很多值會變成無限循環:

十進位     二進位
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 的 Number 只有 64 位,誤差因此更容易被觀察到。以下是在 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

解法:比較前先統一精度

最常見的做法是在比較之前用 toFixed() 把結果收斂到指定位數——因為 toFixed 過程中會自動四捨五入,剛好把尾數的雜訊抹掉:

(1.0 - 0.9).toFixed(10)                    // "0.1000000000"
parseFloat((1.0 - 0.9).toFixed(10)) === 0.1   // True
parseFloat((1.0 - 0.8).toFixed(10)) === 0.2   // True
parseFloat((1.0 - 0.7).toFixed(10)) === 0.3   // True
parseFloat((11.0 - 11.8).toFixed(10)) === -0.8 // True

注意 toFixed() 的位數參數必須介於 0 與 20 之間。

提煉成工具函式

// 判斷兩個數值是否相等(預設精度 10 位)
function isEqual(number1, number2, digits) {
    digits = digits == undefined ? 10 : digits;
    return number1.toFixed(digits) === number2.toFixed(digits);
}

isEqual(1.0 - 0.7, 0.3);   // true

若偏好物件導向風格,也可以擴充 Number.prototype:

Number.prototype.isEqual = function(number, digits) {
    digits = digits == undefined ? 10 : digits;
    return this.toFixed(digits) === number.toFixed(digits);
};

(1.0 - 0.7).isEqual(0.3);  // true

另外兩種思路

  • 整數化運算:金額一律以「分」為單位做整數加減,最後再除以 100 顯示,這是在電商系統裡最可靠的處理方式。
  • 誤差容忍比較:Math.abs(a - b) < Number.EPSILON(或自訂一個微小量),語意上比 toFixed 更貼近「浮點數本來就不精確」的事實。

擴充 prototype 雖方便,但在多人協作或第三方函式庫並存的專案裡容易污染全域,建議優先採用獨立工具函式。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved