用负数格式化货币

Format money with negative number

本文关键字:货币 格式化      更新时间:2023-09-26

我有一个javascript函数,可以很好地处理正数,但当输入负数时,它会警告NaN:

function formatMoney(number) {
        number = parseFloat(number.toString().match(/^'d+'.?'d{0,2}/));
        //Seperates the components of the number
        var components = (Math.floor(number * 100) / 100).toString().split(".");
        //Comma-fies the first part
        components [0] = components [0].replace(/'B(?=('d{3})+(?!'d))/g, ",");
        //Combines the two sections
        return components.join(".");
    }
alert(formatMoney(-11));

下面是jsFiddle中的示例http://jsfiddle.net/longvu/wRYsU/

感谢您的帮助

/^'d+'.?'d{0,2}/中不允许有前导符号,因此必须以数字开头。第一步是允许这样做,比如:

/^-?'d+'.?'d{0,2}/

如果您将放在示例jsfiddle脚本中,您将得到一个-11而不是NaN的对话框。

在我看来,你可以摆脱第一个正则表达式(除非你想验证输入),并使用:

function formatAsMoney(n) {
  n = (Number(n).toFixed(2) + '').split('.');
  return n[0].replace(/'B(?=('d{3})+(?!'d))/g, ",") + '.' + (n[1] || '00');
}

toFixed曾经有过问题,但我认为这已经不是问题了。