把数字转换成货币格式

 

方法一:

 1 Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
 2   places = !isNaN(places = Math.abs(places)) ? places : 2;
 3   symbol = symbol !== undefined ? symbol : "¥";
 4   thousand = thousand || ",";
 5   decimal = decimal || ".";
 6   var number = this,
 7     negative = number < 0 ? "-" : "",
 8     i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
 9     j = (j = i.length) > 3 ? j % 3 : 0;
10   return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
11 };

 

方法二:

/**
  * @date: 转换金额格式 
  * @format:
  */
export function formatMoney(amt, foramat = true, length = 2) {

  if (!isEmpty(amt)) {
    amt = amt + '';
    let zf = '';
    if (amt.charAt(0) == '+' || amt.charAt(0) == '-') {
      zf = amt.charAt(0);
      amt = amt.substr(1);
    }
    amt = parseFloat(amt.replace(/[^\d\.-]/g, "")).toFixed(length) + "";
    var l = amt.split(".")[0].split("").reverse();
    var r = amt.split(".")[1];
    if (foramat) {
      var t = "";
      for (var i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
      }
      l = t.split("");
    }
    if (r) {
      return zf + l.reverse().join("") + "." + r;
    } else {
      return zf + l.reverse().join("");
    }
  } else {
    return '0.00';
  }
}

export function isEmpty(val) {
  if (val === undefined || val === null || val.length === 0) {
    return true;
  }
  return false;
}

 

posted @ 2020-08-19 10:15  思猿客  阅读(486)  评论(0编辑  收藏  举报