| 方法 | 用途 | 範例 |
|---|---|---|
| toFixed(digits) | 固定小數位數(四捨五入) | (1.234).toFixed(2) === "1.23" |
| toExponential(digits) | 科學記號,小數位數 | (1234).toExponential(2) === "1.23e+3" |
| toPrecision(precision) | 有效位數(含整數位) | (1.234).toPrecision(3) === "1.23" |
var n = 12345.6789;
n.toFixed(); // "12346" (預設 0 位,四捨五入)
n.toFixed(1); // "12345.7"
n.toFixed(6); // "12345.678900" (補零)
(1.23e20).toFixed(2); // "123000000000000000000.00"
(1.23e-10).toFixed(2); // "0.00"
2.34.toFixed(1); // "2.3" (注意:2.34 視為數字字面量)
(-2.34).toFixed(1); // "-2.3" (需加括號)
支援度:IE5.5+、所有現代瀏覽器均支援(ES3 起標準化)。
function roundNumber(number, decimals) {
decimals = Number(decimals);
if (decimals < 1) return Math.round(number).toString();
var numStr = number.toString();
if (numStr.indexOf(".") === -1) numStr += ".";
var cutoff = numStr.indexOf(".") + decimals;
var d1 = Number(numStr.charAt(cutoff));
var d2 = Number(numStr.charAt(cutoff + 1));
if (d2 >= 5) {
if (d1 === 9 && cutoff > 0) {
// 進位連鎖處理
while (cutoff > 0 && (d1 === 9 || isNaN(d1))) {
cutoff--;
d1 = Number(numStr.charAt(cutoff));
}
}
d1++;
}
var result = numStr.substring(0, cutoff) + d1;
// 補零
var decPart = result.split(".")[1] || "";
while (decPart.length < decimals) decPart += "0";
return result.split(".")[0] + "." + decPart;
}
num.toFixed(2) 或 Intl.NumberFormat(支援千分位、貨幣、區域設定)。decimal.js 等庫。new Intl.NumberFormat("zh-TW", {minimumFractionDigits:2, maximumFractionDigits:2}).format(num)。