鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ Number.prototype.toLocaleString 的兼容問題

Number.prototype.toLocaleString 的兼容問題

在做金額格式化的時(shí)候用到了 Number.prototype.toLocaleString 這個(gè)方法,但是在一些老版本的瀏覽器中會(huì)出現(xiàn)兼容問題

var a = 10000000;
a.toLocaleString(); 
// chrome 68 "10,000,000" 
// 搜狗瀏覽器 7.5.5 "10,000,000.000"

搜狗 7.5.5 多了 .000
原來的格式化函數(shù)(格式化千分位且保留兩位小數(shù))

formatAmount: function (amount) { // 金額千位格式化
  if (typeof amount === 'undefined' || amount === '') return '';
  if (amount - 0 === 0) return '0.00';
  let num = amount - 0;
  let str = (num-0).toFixed(2); // 保留兩位小數(shù)
  let num_int = str.split('.')[0];
  let num_point = str.split('.')[1];
  return `${(num_int-0).toLocaleString()}.${num_point}`;
}

兼容后

formatAmount: function (amount) { // 金額千位格式化
      if (typeof amount === 'undefined' || amount === '') return '';
      if (amount - 0 === 0) return '0.00';
      let num = amount - 0;
      let str = (num-0).toFixed(2); // 保留兩位小時(shí)
      let num_int = (str.split('.')[0] - 0).toLocaleString();
      let num_point = str.split('.')[1];
      return `${num_int.indexOf('.')>-1?num_int.split('.')[0]:num_int}.${num_point}`;
    }

搜狗 7.5.5 的內(nèi)核版本是 Chromium 49.0.2623
根據(jù)MDN顯示是支持這個(gè)方法的。那這種兼容性該怎么判斷?方法可以用但是返回的結(jié)果不同。

回答
編輯回答
好難瘦
.toLocaleString(undefined,{minimumFractionDigits:0,maximumFractionDigits:0})
2018年1月20日 03:27