JS 金额逗号分隔保留两位小数

  • JS 金额逗号分隔保留两位小数
//判断是否数字
function isNumber(num) {
  return (num + "").match(/^[-]?\d+[.]?\d*$/g);
}

function eraseThousandSplit(num) {
  num = "" + num;
  return num.replace(/,/g, "");
}

//数字千分位,两位小数
function thousandSplitNumber(num) {
  if (num == "" || num == undefined) return "";
  num = eraseThousandSplit(num);
  if (!isNumber(num)) num = 0;
  num = new Number(num).toFixed(2) + "";
  var suffix = "";
  if (num.indexOf(".") != -1) {
    suffix = num.substr(num.lastIndexOf("."));
    num = num.substring(0, num.lastIndexOf("."));
  }
  num = num + ",";
  while (/\d{4}/.test(num)) {
    num = num.replace(/(\d+)(\d{3},)/, "$1,$2");
  }

  return num.substring(0, num.length - 1) + suffix;
}

thousandSplitNumber(23455)

posted @ 2024-05-23 20:28  jiazq  阅读(27)  评论(0)    收藏  举报