js中货币格式化两种方法

直接在Number中扩展货币格式方法

Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
       places = !isNaN(places = Math.abs(places)) ? places : 2;
       symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var number = this,
            negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        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) : "");
    };
    //参数:保留几位小数,货币符号,千位分隔符,小数分隔符
    var a=2345.0000.formatMoney(2,‘‘,‘,‘,‘.‘);
    console.log(a);

货币格式化方法,不用prototype对Number进行拓展的版本

    formatMoney(number, places, symbol, thousand, decimal) {
  number = number || 0;
  places = !isNaN(places = Math.abs(places)) ? places : 2;
  symbol = symbol !== undefined ? symbol : "$";
  thousand = thousand || ",";
  decimal = decimal || ".";
  var negative = number < 0 ? "-" : "",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  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) : "");
},

调用 formatMoney(jjye,4,"¥")

另一种:
formatNum(num) {
return (num + ‘‘).replace(/(\d{1,3})(?=(\d{3})+(?:$|.))/g, ‘$1,‘);
},

js中货币格式化两种方法

上一篇:webpack原理


下一篇:创建Flash站点的十大可用性技巧汇总