2024年8月19日 星期一

再探 Intl.NumberFormat 的進位原則

 再探 Intl.NumberFormat 的進位原則

前言

  在 調整 Intl.NumberFormat 的進位原則  探索了部分參數的使用,這次把剩下的參數也試用一下,在此把學習的過程做個紀錄。


內容

  範例如下

console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfCeil'
  }).format( -10.56) );//-10.6 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfExpand'
  }).format( -10.54) );//-10.5 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfFloor'
  }).format( -10.54) );//-10.5 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfTrunc'
  }).format( -10.56) );//-10.6 公升
//
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfEven'
  }).format( -10.56) );//-10.6 公升
console.log( new Intl.NumberFormat('zh-TW', { 
  style: 'unit', 
  unit : 'liter',
  unitDisplay : 'long',
  maximumFractionDigits : 1,
  roundingMode : 'halfEven'
  }).format( -10.45) );//-10.4 公升


剩下的參數為 halfCeil 、 halfExpand 、halfFloor 、 halfTrunc 與 halfEven ,這次的參數不是很容易懂,halfCeil 在正值時採取"四捨五入",負值時採取"六進五捨",halfCeil 的正值與負值一樣採用"四捨五入",也是預設的參數,halfFloor  在正值時採取"六進五捨" ,負值則採用"四捨五入",halfTrunc 則是正值與負值一樣採用"六進五捨",最後一個參數 halfEven ,如果進位的數字本身已是奇數結果會和 halfExpand 一樣,範例的 -10.56  裡的進位數字是 5 ,所以進位發生,但如果把數字換成 -10.45 ,這時進位數字是 4 ,也就是偶數,這時所有的進位都不會發生,可以把 halfEven  想成是只有進位數是奇數時才採取"四捨五入"。


參考資料

[ developer.mozilla.org ] Intl.NumberFormat


相關文章與資料

調整 Intl.NumberFormat 的進位原則

沒有留言:

張貼留言