美文网首页
将数字转成钱的格式

将数字转成钱的格式

作者: tenro | 来源:发表于2021-09-09 16:00 被阅读0次

Number上做扩展

/**
      places:  保留小数点位数(默认:  保留2位)
      symbol:    货币符号(默认: '$')
      thousand:   大于1000以上每3位用什么符号拼接 (默认: ‘,’)
      decimal:  小数点的符号替换(默认:  '.' )
*/
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 revenue = 12345678976543221;
revenue.formatMoney()    // $12,345,678,976,543,220.00
revenue.formatMoney(2, '¥', '*', '&')。      //  "¥12*345*678*976*543*220&000000"

函数实现

function 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) : "");
}

相关文章

网友评论

      本文标题:将数字转成钱的格式

      本文链接:https://www.haomeiwen.com/subject/ksoiwltx.html