阅读 72

js 数字三位加逗号(兼容负数,小数)

function toThousands(num) {
  var num = (num || 0).toString(),
    re = /\d{3}$/,
    result = "";
    var point = ''
  if (num.indexOf(".") !== -1) {
    point = num.substring(num.indexOf("."))
    num = parseInt(num)

  }
  while (re.test(num)) {
    result = RegExp.lastMatch + result;
    if (num !== RegExp.lastMatch) {
      result = "," + result;
      num = RegExp.leftContext;
    } else {
      num = "";
      break;
    }
  }
  if (num) {
    result = num + result;
  }

  function _(result) {
    return result.replace("-,", "-")
  }
  function __(result) {
     if (result[0] === ",") {
    result = result.substring(1)
    }
    return result
  }
  function ___(result) {
    if (result[0] === ".") {
      result = "0" + result
    }
    return result
  }
  return ___(__(_(result) + point))   ;
}
复制代码