2024年7月1日 星期一

初探 Intl.NumberFormat.formatToParts()

 初探 Intl.NumberFormat.formatToParts()

前言

   Intl.NumberFormat 可以顯示數值,但如果只需要小數的部分有辦法做到嗎?可以透過 Intl.NumberFormat.formatToParts() 來達成,在此把學習的過程做個紀錄。


內容

  範例如下

let parts = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
}).formatToParts( 123.45 );
console.log(parts);
//[[object Object] {
//   type: "currency",
//   value: "$"
// }, [object Object] {
//   type: "integer",
//   value: "123"
// }, [object Object] {
//   type: "decimal",
//   value: "."
// }, [object Object] {
//   type: "fraction",
//   value: "45"
// }]
//
partValues = parts.map((p) => p.value);
console.log(partValues);//["$", "123", ".", "45"]


Intl.NumberFormat.formatToParts()  的回傳值是個陣列,不過裡面的內容會含有每個部位的名稱,如果不需要可以透過 map() 來過濾,如同範例的 partValues ,這樣就可以方便提取各部位。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat