js千分位格式化

  • 方法一(非正则, 字符串):


var test = "1234567890";

function formatCash(str) {
  str = (str || 0).toString();
  if (str.length <= 1) {
    return str;
  }
  var arr = [];

  for (var i = 1, len = str.length; i < len; i++) {
    if (str.length % 3 && i === 1) {
      arr.push(str.substr(0, str.length % 3));
    }
    if (i % 3 === 0) {
      arr.push(str.substr(i - 2, 3));
    }
  }
  return arr.join(",");
}

console.log(formatCash(test));
  • 方法二(非正则,数组):


var test = "1234567890";

function formatCash(str) {
  var arr = [];
  var counter = 0;
  str = (str || 0).toString().split("");
  for (var i = str.length - 1; i >= 0; i--) {
    counter++;
    arr.unshift(str[i]);
    if (!(counter % 3) && i !== 0) {
      arr.unshift(",");
    }
  }
  return arr.join("");
}

console.log(formatCash(test));


无名小子
643 声望23 粉丝

没时间解释了,大家快上车