2024年7月29日 星期一

調整 Intl.NumberFormat 的顯示數字的格式

 調整 Intl.NumberFormat 的顯示數字的格式

前言

  電子工程常常把 1000 記為 K ,百萬記為 M , Intl.NumberFormat 支援這樣的顯示方式嗎?答案是可行的,而且只需透過簡單的參數調整即可完成,在此把學習的過程做個紀錄。


內容

  範例如下

let numFormatStandard = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  notation:'standard',
});

console.log( numFormatStandard.format(10000) );//$10,000.00
//
let numFormatScientific = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  notation:'scientific',
});

console.log( numFormatScientific.format(10000) );//$1.00E4
//
let numFormatEngineering = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  notation:'engineering',
});

console.log( numFormatEngineering.format(10000) );//$10.00E3
//
let numFormatCompact = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  notation:'compact',
});

console.log( numFormatCompact.format(10000) );//$10K


透過 notation 參數可以調整顯示數字的格式,參數有 standard 、scientific 、engineering 與 compact , standard  就是預設值,也是最常見的狀況,scientific  與 engineering 的格式都是在數字末端加 E 來表達,由於我本身對這種格式不熟,就不多作介紹,最後是 compact  ,這個格式就是 1000 記為 K ,百萬記為 M 的顯示格式。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat

沒有留言:

張貼留言