数字添加逗号分割符

50 阅读1分钟
//1.字符串转换为字符串数组,循环整个数组,每三位添加一个分割逗号,然后在合并为字符串,逗号是从后往前加的
function numFormat(num) {
     num = num.toString().split(".");
     let arr = num[0].split("").reverse();
     let res = [];
     for (let i = 0; i <arr.length; i++) {
          if (i%3 === 0 && i!==0) {
               res.push(",")
          }
          res.push(arr[i]);
     }

     res.reverse();
     if (num[1]) {
          res = res.join("").concat("."+num[1]);
     } else {
         res= res.join("")
     }
     return res;
}

var a=1234567894532;
var b=673439.4542;
console.log(numFormat(a)); // "1,234,567,894,532"
console.log(numFormat(b)); // "673,439.4542"