Number.prototype.toFixed()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

toFixed() 方法 Number 值,返回一個字串,表示此數字使用 定點表示法,並帶有指定的小數位數。

試一試

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial("1.23e+5"));
// Expected output: "123000.00"

語法

js
toFixed()
toFixed(digits)

引數

digits 可選

小數點後要顯示的數字位數;值應介於 0100 之間(含)。如果省略此引數,則視為 0

返回值

一個字串,表示給定數字的定點表示法。當數字的絕對值大於或等於 1021 時,會使用科學記數法(返回值與 Number.prototype.toString() 相同)。

異常

RangeError

如果 digits 不在 0100 之間(含),則丟擲錯誤。

TypeError

如果此方法在非 Number 物件上呼叫,則丟擲該錯誤。

描述

toFixed() 方法返回一個不使用 指數記數法 且小數點後恰好有 digits 位數字的數字的字串表示形式。如果需要,數字會被四捨五入,如果需要,小數部分會用零填充,使其具有指定的長度。

如果數字的絕對值大於或等於 1021,則此方法使用與 Number.prototype.toString() 相同的演算法,並返回一個指數記數法的字串。如果數字的值是無限的,toFixed() 會返回 "Infinity""NaN""-Infinity"

對於某些值,toFixed() 的輸出可能比 toString() 更精確,因為 toString() 只會輸出足夠的有效數字來區分該數字與其他相鄰的數字值。例如:

js
(1000000000000000128).toString(); // '1000000000000000100'
(1000000000000000128).toFixed(0); // '1000000000000000128'

但是,選擇過高的 digits 精度可能會返回意外結果,因為十進位制分數不能在浮點數中精確表示。例如:

js
(0.3).toFixed(50); // '0.29999999999999998889776975374843459576368331909180'

示例

使用 toFixed()

js
const numObj = 12345.6789;

numObj.toFixed(); // '12346'; rounding, no fractional part
numObj.toFixed(1); // '12345.7'; it rounds up
numObj.toFixed(6); // '12345.678900'; additional zeros
(1.23e20).toFixed(2); // '123000000000000000000.00'
(1.23e-10).toFixed(2); // '0.00'
(2.34).toFixed(1); // '2.3'
(2.35).toFixed(1); // '2.4'; it rounds up
(2.55).toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
(2.449999999999999999).toFixed(1); // '2.5'
// it rounds up as it's less than Number.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45

(6.02 * 10 ** 23).toFixed(50); // '6.019999999999999e+23'; large numbers still use exponential notation

使用 toFixed() 處理負數

由於成員訪問的 優先順序 高於一元減號,因此您需要對負數表示式進行分組才能得到字串。

js
-2.34.toFixed(1); // -2.3; a number
(-2.34).toFixed(1); // '-2.3'

規範

規範
ECMAScript® 2026 語言規範
# sec-number.prototype.tofixed

瀏覽器相容性

另見