js 每三位数添加逗号

function toThousands(num) {
  num = (num || 0).toString();
  let number = 0,
      floatNum = ‘‘,
      intNum = ‘‘;
  // 判断是否有小数位,有则截取小数点后的数字
  if (num.indexOf(‘.‘) > 0) {
    number = num.indexOf(‘.‘); // 获取小数点出现的位置
    floatNum = num.substr(number); // 截取arr.substr(form, length)
    intNum = num.substring(0,number); // 截取arr.substring(start, end)
  } else {
    intNum = num;
  }
  let result = [],
      counter = 0;
  intNum = intNum.split(‘‘);
  // 利用3的倍数,向数组插入‘,‘
  for (let i = intNum.length - 1; i >= 0; i--) {
    counter++;
    result.unshift(intNum[i]);
    if (!(counter % 3) && i != 0) { result.unshift(‘,‘); }
  }
  return result.join(‘‘) + floatNum || ‘‘;
}
 
let A1 = 1234567890122;
let A2 = 1234567890122.122;
console.log(toThousands(A1)); //1,234,567,890,122
console.log(toThousands(A2)); // 1,234,567,890,122.122

 

js 每三位数添加逗号

上一篇:CSS 数字


下一篇:百度WebUploader实现浏览器端大文件分块上传