js实现货币数字格式化的方法

735 阅读1分钟
function toThousands(num) {
  var result = [ ], counter = 0;
  num = (num || 0).toString().split('');
  console.log(num); // [ '2', '3', '1', '2', '3', '2', '1', '3', '1' ]
  for (var i = num.length - 1; i >= 0; i--) {
      counter++;
      result.unshift(num[i]);
      if (!(counter % 3) && i != 0) { result.unshift(','); }
  }
  return result.join('');
}
const res = toThousands(231232131)
console.log(res); // 231,232,131