在我们程序处理金钱的时候,有时候在使用JavaScript的计算的时候很容易出现问题,如果数字很大的话往往会出现显示不好看的问题,所以小编在这里封装了一个格式化金钱的方法。

function formatCurrency(num, withcents) {
    var originnum = num;
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) {
        num = "0";
    }
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    var cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10) {
        cents = "0" + cents;
    }
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }
    var rs = (((sign) ? '' : '-') + num + '.' + cents);
    if (!withcents && parseInt(originnum) == parseFloat(originnum)) {
        return rs.split('.')[0];
    } else {
        return rs;
    }
}

参数:

  • num:金钱的金额
  • withcents:是否补全分(即小数点后的两位)
Last modification:September 13, 2019
If you think my article is useful to you, please feel free to appreciate