2024年6月10日 星期一

調整 Intl.NumberFormat 正負號顯示

 調整 Intl.NumberFormat 正負號顯示

前言

  使用  Intl.NumberFormat 時,當數值是負的時候才顯示負號,這是常見的狀況,但如果碰到特殊狀況時可以改嗎?答案是可以的,在此把學習的過程做個紀錄。


內容

  範例如下

let number = 100;
let numberZ = 0;
let numberN = -100;
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'auto',
  }).format( number) );//100 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'auto',
  }).format( numberZ) );//0 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'auto',
  }).format( numberN) );//-100 升
//
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'always',
  }).format( number) );//+100 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'always',
  }).format( numberZ) );//+0 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'always',
  }).format( numberN) );//-100 升

//
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'exceptZero',
  }).format( number) );//+100 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'exceptZero',
  }).format( numberZ) );//0 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'exceptZero',
  }).format( numberN) );//-100 升
//
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'negative',
  }).format( number) );//100 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'negative',
  }).format( numberZ) );//0 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'negative',
  }).format( numberN) );//-100 升
//
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'never',
  }).format( number) );//100 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'never',
  }).format( numberZ) );//0 升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  signDisplay : 'never',
  }).format( numberN) );//100 升


透過 signDisplay 可以調整正負號顯示,參數有 auto 、 always 、 exceptZero 、 negative 與 never , auto 就是預設,也是常見的只在負值時顯示負號 ,always 則是無論如何都顯示正負號,包含 0 ,exceptZero 也是都顯示正負號,但 0 的時候不顯示 ,negative 則是指在負值顯示,這行為和 auto 是一樣的,never 則是無論如何都不顯示正負號。範例都是用顯示單位的方式使用,但這個參數不只作用在單位顯示,在百分比與貨幣時一樣適用。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat


相關文章與資料

使用 Intl.NumberFormat 顯示單位

沒有留言:

張貼留言