2024年6月24日 星期一

使用 Intl.NumberFormat 顯示數值範圍

 使用 Intl.NumberFormat  顯示數值範圍

前言

  Intl.NumberFormat 不只可以顯示單一數值,也支援顯示數值範圍,在此把學習的過程做個紀錄。


內容

  範例如下

console.log( new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  //maximumFractionDigits: 0,
}).formatRange(3 , 5) );//$3.00 – $5.00
//
console.log( new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
}).formatRange(3 , 5) );//$3 – $5
//
console.log( new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
}).formatRange(3.5 , 5.5) );//$4 – $6
//
console.log( new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
}).formatRange(3.4 , 5.4) );//$3 – $5
//
console.log( new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
}).formatRange(3.5 , 4.4) );//~$4


要顯示數值範圍可以透過 Intl.NumberFormat.formatRange() ,參數就是兩個 Number,個別是範圍的開頭與範圍的結束,第一例就簡單地使用顯示數值範圍,第二例搭配先前的 在 Intl.NumberFormat 控制顯示位數 ,可以控制顯示小數位數,顯示的數值如果低於精度會採取四捨五入的原則來顯示,這點可以在第三例與與第四例看到,第五例比較特別,如果範圍差在最低精度時,且範圍開頭會被五入,這樣就會被顯示成近似於數值,這是 Intl.NumberFormat.formatRange() 相當特別的規則。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat


相關文章與資料

在 Intl.NumberFormat 控制顯示位數

沒有留言:

張貼留言