Chrome/Firefox 中頭toFixed方法四舍五入兼容性問題


每個Number的toFixed()方法可把 Number 四舍五入為指定小數位數的數字。四舍五入顧名思義,4及以下舍去,5及以上加1。

 

四舍

1.31.toFixed(1) // 1.3
1.32.toFixed(1) // 1.3
1.33.toFixed(1) // 1.3
1.34.toFixed(1) // 1.3

 

五入

1.35.toFixed(1) // 1.4
1.36.toFixed(1) // 1.4
1.37.toFixed(1) // 1.4
1.38.toFixed(1) // 1.4
1.39.toFixed(1) // 1.4

 

IE6-10

1.35.toFixed(1) // 1.4 正確
1.335.toFixed(2) // 1.34  正確
1.3335.toFixed(3) // 1.334 正確
1.33335.toFixed(4) // 1.3334 正確
1.333335.toFixed(5)  // 1.33334 正確
1.3333335.toFixed(6) // 1.333334 正確

 

但在 chrome44/firefox41 里對於最后一位是 5 的有時竟然沒有進位

1.35.toFixed(1) // 1.4 正確
1.335.toFixed(2) // 1.33  錯誤
1.3335.toFixed(3) // 1.333 錯誤
1.33335.toFixed(4) // 1.3334 正確
1.333335.toFixed(5)  // 1.33333 錯誤
1.3333335.toFixed(6) // 1.333333 錯誤

可以看到,小數點位數為2,5時四舍五入是正確的,其它是錯誤的。

 

如果最后一位為非 5 ,chrome44/firefox41 則沒有這個問題

1.36.toFixed(1) // 1.4 正確
1.336.toFixed(2) // 1.34  正確
1.3336.toFixed(3) // 1.334 正確
1.33336.toFixed(4) // 1.3334 正確
1.333336.toFixed(5)  // 1.33334 正確
1.3333336.toFixed(6) // 1.333334 正確

 

修復方式

/*
 * 修復 firefox/chrome 中 toFixed 兼容性問題
 * firefox/chrome 中,對於小數最后一位為 5 時進位不正確,修復方式即判斷最后一位為 5 的,改成 6, 再調用 toFixed
 */
function toFixed(number, precision) {
    var str = number + ''
    var len = str.length
    var last = str.substr(len-1, len)
    if (last == '5') {
        last = '6'
        str = str.substr(0, len-1) + last
        return (str - 0).toFixed(precision)        
    } else {
        return number.toFixed(precision)
    }
}

 

2015.10.26 補充:Firefox 和 Chrome的實現沒有問題,根本原因是計算機里浮點數精度丟失問題。修復方式改為

// toFixed 修復
function toFixed(num, s) {
	var times = Math.pow(10, s)
	var des = num * times + 0.5
	des = parseInt(des, 10) / times
	return des + ''
}

  

相關:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

https://es5.github.io/#x15.7.4.5


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM