2024年8月12日 星期一

調整 Intl.NumberFormat 的進位原則

 調整 Intl.NumberFormat 的進位原則

前言

  Intl.NumberFormat 的進位原則是可以透過參數調整的,在此把學習的過程做個紀錄。


內容

  範例如下

let numFormat = new Intl.NumberFormat("zh-TW", {
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,

});
//
console.log( numFormat.format(10.54) );//10.5 公升
console.log( numFormat.format(10.55) );//10.6 公升

//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'ceil'
  }).format( -10.54) );//-10.5 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'expand'
  }).format( -10.54) );//-10.6 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'floor'
  }).format( -10.51) );//-10.6 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'trunc'
  }).format( -10.51) );//-10.5 公升


範例開頭示範不調整時會以四捨五入為原則來調整,如果要調整原則要透過 roundingMode 參數來調整,由於參數有點多,這次介紹 ceil 、expand 、 floor 與 trunc 這四個參數,ceil 與 expand 可以簡化成"無條件進位",那分兩個的意義呢?主要差異在負數時的進位, ceil 會進位到 -10.5 ,但 expand 會進位到 -10.6 , floor 與 trunc 也是一樣的關係,理解成無條件捨棄,但在負數時的原則會不一樣, floor 會捨棄到 -10.6 , trunc 則是 -10.5 。

  

參考資料

[ developer.mozilla.org ] Intl.NumberFormat

沒有留言:

張貼留言