2024年7月15日 星期一

注意 初探 Intl.NumberFormat.formatRangeToParts() 輸出不一定是範圍

 注意 初探 Intl.NumberFormat.formatRangeToParts() 輸出不一定是範圍

前言

  在先前的 初探 Intl.NumberFormat.formatRangeToParts() 基本的使用了 formatRangeToParts() ,在更之前的 使用 Intl.NumberFormat 顯示數值範圍 也是顯示範圍,但它可能會顯示近似值,formatRangeToParts()  也是如此嗎?是的,在此把學習的過程做個紀錄。


內容

  範例如下

let parts = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
}).formatRangeToParts( 3.5 , 4.4);

console.log(parts);


// [[object Object] {
//   source: "shared",
//   type: "approximatelySign",
//   value: "~"
// }, [object Object] {
//   source: "shared",
//   type: "currency",
//   value: "$"
// }, [object Object] {
//   source: "shared",
//   type: "integer",
//   value: "4"
// }]


partValues = parts.map((p) => p.value);
console.log(partValues);//["~", "$", "4"]


formatRangeToParts()  也是會有顯示近似值的狀況,設好 maximumFractionDigits ,就可能發生顯示近似值,如範例示範的範圍,如果只想取數值一樣透過 map() 來處理,使用 Intl.NumberFormat.formatRangeToParts() 要考慮有顯示近似值的可能。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat


相關文章與資料

初探 Intl.NumberFormat.formatRangeToParts()

使用 Intl.NumberFormat 顯示數值範圍

沒有留言:

張貼留言