js 中数字加逗号处理(每三位加逗号)?

前言,面试中遇到将数字增加“,”,方便区分位数,这里记录一下,以便后续用到

1、正则表达式:正则替换

// 正则表达式
const toThousands = (num = 0) => {
   return num.toString().replace(/\d+/, function(n) {
      return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
   });
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111

2、字符串排序:倒序排列

// 字符串递归方法
const toThousands = (num = 0) => {
   let result = '';
   let numArr = num.toString().split('.');
   let int = numArr[0];
   let decmial = numArr[1] ? '.' + numArr[1] : '';
   for (let n = int.length - 1; n >= 0; n--) {
      result += int[int.length - n - 1];
      if ((int.length - n - 1) % 3 === 0 && n !== 0) {
         result += ',';
      }
   }
   return result + decmial;
};

console.log(toThousands(1234567890.111)); //1,234,567,890.111

3、字符串模板:使用slice不断截取,不断分割

function toThousands(num = 0) {
   let result = '';
   let numArr = num.toString().split('.');
   let int = numArr[0];
   let decmial = numArr[1] ? '.' + numArr[1] : '';
   while (int.length > 3) {
      result = ',' + int.slice(-3) + result;
      int = int.slice(0, int.length - 3);
   }
   if (int) {
      result = int + result;
   }
   return result + decmial;
}

console.log(toThousands(1234567890.111));

综上所述,计算所耗时间,可见一个问题代码短不一定性能就好,推荐使用第二种方法

方法一 方法二 方法三
1.822 0.104 0.118

 

 

posted @ 2021-02-04 20:41  程序員劝退师  阅读(2535)  评论(0编辑  收藏  举报