1

正の数でうまく機能する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/の例を次に示します。

助けてくれてありがとう

4

2 に答える 2

5

の先頭の符号は許可されて/^\d+\.?\d{0,2}/いません。数字で始める必要があります。

最初のステップは、次のようなものでそれを許可することです:

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

これをサンプルの jsfiddle スクリプトに配置すると、ダイアログ ボックスが表示され-11NaN.

于 2013-06-19T02:21:54.863 に答える
0

最初の正規表現を削除して(入力を検証したくない場合)、次を使用できるように思えます。

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

toFixedに問題がありましたが、もう問題ないと思います。

于 2013-06-19T02:47:06.217 に答える