格式化负数的钱

时间:2013-06-19 02:18:07

标签: javascript

我有一个适用于正数的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/

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

/^\d+\.?\d{0,2}/中没有允许使用前导符号,必须以数字开头。

第一步是允许这样做,例如:

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

如果您在示例jsfiddle脚本中放置 ,则会出现一个包含-11而不是NaN的对话框。

答案 1 :(得分:0)

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

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

toFixed 曾经出现问题,但我不认为这是一个问题。

相关问题