2024年8月5日 星期一

調整 Intl.NumberFormat 的顯示小數的原則

 調整 Intl.NumberFormat 的顯示小數的原則

前言

  Intl.NumberFormat 在顯示美金時會顯示到小數第二位,但如果需要有小數時才顯示小數可行嗎?查了一下可以透過參數調整完成,在此把學習的過程做個紀錄。


內容

  範例如下

let numFormatAuto = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  trailingZeroDisplay : 'auto',
});

console.log( numFormatAuto.format(10000) );//$10,000.00
//
let numFormatStripIfInteger = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  trailingZeroDisplay : 'stripIfInteger'
});

console.log( numFormatStripIfInteger.format(10000) );//$10,000
console.log( numFormatStripIfInteger.format(10000.25) );//$10,000.25

//
let numFormat = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits : 0
});

console.log( numFormat.format(10000.25) );//$10,000




要調整顯示小數的原則是透過 trailingZeroDisplay ,參數有 auto 與 stripIfInteger ,auto 就是預設值,如範例會顯示到小數第二位,使用 stripIfInteger 後,當數值是整數時就不在顯示小數,當有小數時還是會顯示小數,也許你會想到可以透過 maximumFractionDigits 來做到不顯示小數,但使用 maximumFractionDigits  會變成無論如何都不顯示小數,和 stripIfInteger  是不一樣的。



參考資料

[ developer.mozilla.org ] Intl.NumberFormat

沒有留言:

張貼留言