格式化负数的钱

Lon*_* Vu 1 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));
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助

pax*_*blo 5

没有允许领先的登录/^\d+\.?\d{0,2}/,它必须以数字开头.

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

/^-?\d+\.?\d{0,2}/
Run Code Online (Sandbox Code Playgroud)

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