Intl.NumberFormat.prototype.formatToParts()
formatToParts() 方法用於 Intl.NumberFormat 例項,它返回一個物件陣列,這些物件代表由 format() 返回的格式化字串的每個部分。這對於根據本地化標記構建自定義字串非常有用。
試一試
const amount = 654321.987;
const options = { style: "currency", currency: "USD" };
const numberFormat = new Intl.NumberFormat("en-US", options);
const parts = numberFormat.formatToParts(amount);
const partValues = parts.map((p) => p.value);
console.log(partValues);
// Expected output: "["$", "654", ",", "321", ".", "99"]"
語法
formatToParts(number)
引數
返回值
一個包含格式化數字部分的物件陣列。每個物件有兩個屬性:type 和 value,每個屬性都包含一個字串。按順序連線 value 字串將得到與 format() 相同的字串。type 可能是以下之一:
literal-
格式模式中的任何字串部分;例如
" "。請注意,像小數點分隔符或加/減號這樣的常見標記有自己的標記型別。 integer-
數字的整數部分,如果使用分組(由
options.useGrouping控制)則為其一部分。 group-
分組分隔符字串,例如
","。僅在使用分組時出現(由options.useGrouping控制)。 decimal-
小數點分隔符字串,例如
"."。僅在fraction存在時出現。 fraction-
數字的小數部分。
compact-
緊湊型指數,例如
"M"或"thousands"。僅當options.notation為"compact"時出現。形式("short"或"long")可以透過options.compactDisplay控制。 exponentSeparator-
指數分隔符,例如
"E"。僅當options.notation為"scientific"或"engineering"時出現。 exponentMinusSign-
指數負號字串,例如
"-"。僅當options.notation為"scientific"或"engineering"且指數為負數時出現。 exponentInteger-
指數的整數值。僅當
options.notation為"scientific"或"engineering"時出現。 nan-
表示
NaN的字串,例如"NaN"。當數字是NaN時,這是表示數字本身的唯一標記。 infinity-
表示
Infinity或-Infinity的字串,例如"∞"。當數字是Infinity或-Infinity時,這是表示數字本身的唯一標記。 plusSign-
加號,例如
"+"。 minusSign-
減號,例如
"-"。 percentSign-
百分號,例如
"%"。僅當options.style為"percent"時出現。 unit-
單位字串,例如
"l"或"litres"。僅當options.style為"unit"時出現。形式("short"、"narrow"或"long")可以透過options.unitDisplay控制。 currency-
貨幣字串,例如
"$"、"€"、"Dollar"或"Euro"。僅當options.style為"currency"時出現。形式("code"、"symbol"、"narrowSymbol"或"name")可以透過options.currencyDisplay控制。 unknown-
保留給任何未被識別為上述標記的標記;應很少遇到。
示例
使用 formatToParts()
format() 方法輸出本地化的、不透明的字串,無法直接操作
const number = 3500;
const formatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
formatter.format(number);
// "3.500,00 €"
但是,在許多使用者介面中,您可能希望自定義此字串的格式,或將其與其他文字交織。formatToParts() 方法將相同的資訊分解為部分。
formatter.formatToParts(number);
// return value:
[
{ type: "integer", value: "3" },
{ type: "group", value: "." },
{ type: "integer", value: "500" },
{ type: "decimal", value: "," },
{ type: "fraction", value: "00" },
{ type: "literal", value: " " },
{ type: "currency", value: "€" },
];
現在資訊是分開提供的,可以以自定義的方式重新格式化和連線。例如,可以使用 Array.prototype.map()、箭頭函式、switch 語句、模板字面量 和 Array.prototype.join() 來為某些元件插入額外的標記。
const numberString = formatter
.formatToParts(number)
.map(({ type, value }) => {
switch (type) {
case "currency":
return `<strong>${value}</strong>`;
default:
return value;
}
})
.join("");
console.log(numberString);
// "3.500,00 <strong>€</strong>"
規範
| 規範 |
|---|
| ECMAScript® 2026 國際化 API 規範 # sec-intl.numberformat.prototype.formattoparts |
瀏覽器相容性
載入中…