首頁  >  文章  >  web前端  >  為什麼 toFixed(2) 對某些小數值的捨入不正確?

為什麼 toFixed(2) 對某些小數值的捨入不正確?

Patricia Arquette
Patricia Arquette原創
2024-10-22 14:40:02417瀏覽

Why is toFixed(2) Rounding Incorrectly for Certain Decimal Values?

Javascript toFixed 舍入差異

toFixed(2) 未對某些十進位值進行捨入,在提供的範例中顯示859.38而不是859.39 。這種差異可歸因於 toFixed() 方法的瀏覽器所實現的差異。

要避免此問題並確保跨瀏覽器的捨入一致,請考慮使用 blg 建議的 toFixed10() 方法。即使對於擴展的精度值,此方法也能提供準確的捨入。

以下是包含 toFixed10() 的更新程式碼片段:

function toFixed(num, precision) {
    return (+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
}
...
$('#lblTotalSprice').text('$' + addCommas(toFixed(currSprice, 2)));
$('#lblTotalPrice').text('$' + addCommas(toFixed(currPrice, 2)));
$('#lblTotalDiscount').text('$' + addCommas(toFixed(currDiscount, 2)));
$('#lblTotalDeposit').text('$' + addCommas(toFixed(currDeposit, 2)));

以上是為什麼 toFixed(2) 對某些小數值的捨入不正確?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn