金额转换成千分位表示(支持负数)

function money2Thousand(s, n) {
  n = n >= 0 && n <= 20 ? n : 2;
  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var l = s.split(".")[0].split("").reverse(),
      r = s.split(".")[1];
  r = r == null ? "" : "." + r;
  var t = "";
  if (l[l.length - 1] === '-') {//负数不需要分隔号,
    for (var i = 0; i < l.length; i++) {
      if (l[i]==='-') {
        t += l[i]+"";
        continue;
      }
      //不是数组的倒数第二个元素才加"," ["0", "4", "5", "-"]
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length-1 ? "," : "");
    }
  } else {
    for (var i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
    }
  }
  return ( t.split("").reverse().join("") + r);
}

你可能感兴趣的:(金额转换成千分位表示(支持负数))