萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 數字保留小數位:toFixed、toExponential、toPrecision 與自訂四捨五入

內建方法

方法用途範例
toFixed(digits)固定小數位數(四捨五入)(1.234).toFixed(2) === "1.23"
toExponential(digits)科學記號,小數位數(1234).toExponential(2) === "1.23e+3"
toPrecision(precision)有效位數(含整數位)(1.234).toPrecision(3) === "1.23"

toFixed 詳細行為

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 起標準化)。

自訂四捨五入函式(教學用,生產請用 toFixed)

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)。
copyright © 萬盛學電腦網 all rights reserved