Intl.NumberFormat.prototype.format()

Baseline 廣泛可用 *

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2017 年 9 月以來,它已在瀏覽器中提供。

* 此特性的某些部分可能存在不同級別的支援。

format() 方法是 Intl.NumberFormat 例項的一部分,它根據此 Intl.NumberFormat 物件的 區域設定和格式化選項來格式化數字。

試一試

const amount = 654321.987;

const options1 = { style: "currency", currency: "RUB" };
const numberFormat1 = new Intl.NumberFormat("ru-RU", options1);

console.log(numberFormat1.format(amount));
// Expected output: "654 321,99 ₽"

const options2 = { style: "currency", currency: "USD" };
const numberFormat2 = new Intl.NumberFormat("en-US", options2);

console.log(numberFormat2.format(amount));
// Expected output: "$654,321.99"

語法

js
format(number)

引數

數字

一個 NumberBigInt 或字串,用於格式化。字串的解析方式與 數字轉換 中相同,不同之處在於 format() 將使用字串表示的精確值,避免在隱式轉換為數字時丟失精度。

注意: 規範的舊版本將字串解析為 Number。請檢視您瀏覽器的相容性表格。

返回值

一個字串,表示根據此 Intl.NumberFormat 物件的區域設定和格式化選項格式化後的給定 number

注意: 大多數情況下,format() 返回的格式是一致的。然而,輸出可能因實現而異,即使在同一區域設定下也是如此 — 輸出差異是故意的,並且規範允許。它也可能不是您期望的。例如,字串可能使用不間斷空格,或者被雙向控制字元包圍。您不應將 format() 的結果與硬編碼的常量進行比較。

描述

JavaScript 中的 Number 值如果太大或太小,會丟失精度,導致文字表示不準確。如果您正在對大於 Number.MAX_SAFE_INTEGER 的整數進行計算,您應該改用 BigInt,它會正確格式化。

js
new Intl.NumberFormat("en-US").format(1234567891234567891); // 1,234,567,891,234,568,000
new Intl.NumberFormat("en-US").format(1234567891234567891n); // 1,234,567,891,234,567,891

您也可以傳遞非常大的字串以作為任意精度十進位制字串進行格式化(如果您要對資料進行計算,您仍然需要使用 BigInt)。

js
new Intl.NumberFormat("en-US").format("1234567891234567891"); // 1,234,567,891,234,567,891

示例

使用格式

使用 format getter 函式來格式化單個貨幣值。下面的程式碼演示瞭如何為俄羅斯區域設定格式化盧布貨幣。

js
const options = { style: "currency", currency: "RUB" };
const numberFormat = new Intl.NumberFormat("ru-RU", options);
console.log(numberFormat.format(654321.987));
// "654 321,99 ₽"

使用 `format` 和 `map`

使用 format getter 函式來格式化陣列中的所有數字。請注意,該函式已繫結到其從中獲取的 Intl.NumberFormat 物件,因此可以直接傳遞給 Array.prototype.map。這被認為是一個歷史遺留問題,是當前不再遵循的約定的一部分,但為了保持與現有程式的相容性而保留。

js
const a = [123456.789, 987654.321, 456789.123];
const numberFormat = new Intl.NumberFormat("es-ES");
const formatted = a.map((n) => numberFormat.format(n));
console.log(formatted.join("; "));
// "123.456,789; 987.654,321; 456.789,123"

使用 `format` 和字串

使用字串,我們可以指定大於 Number.MAX_SAFE_INTEGER 的數字,而不會丟失精度。

js
const numberFormat = new Intl.NumberFormat("en-US");

// Here the value is converted to a Number
console.log(numberFormat.format(987654321987654321));
// 987,654,321,987,654,300

// Here we use a string and don't lose precision
console.log(numberFormat.format("987654321987654321"));
// 987,654,321,987,654,321

我們也可以使用通用的“E”指數語法表示十進位制字串:#.#E#。下面的程式碼建立了一個 BigInt,將其轉換為帶字尾 E-6 的字串,然後進行格式化。

js
const numberFormat = new Intl.NumberFormat("en-US");
const bigNum = 1000000000000000110000n;
console.log(numberFormat.format(bigNum));
// "1,000,000,000,000,000,110,000"

// Format as a string using the `E` syntax:
console.log(numberFormat.format(`${bigNum}E-6`));
// "1,000,000,000,000,000.11"

規範

規範
ECMAScript® 2026 國際化 API 規範
# sec-intl.numberformat.prototype.format

瀏覽器相容性

另見