81

マスクは必要ありませんが、(すべてのブラウザーで) 通貨をフォーマットし、文字や特殊文字を入力できないようにするものが必要です。助けてくれてありがとう

例:

有効: $50.00
$1,000.53

無効: $w45.00
$34.3r6

4

7 に答える 7

104

別のオプション (ASP.Net カミソリ ビューを使用している場合) は、ビューで実行できます。

<div>@String.Format("{0:C}", Model.total)</div>

これにより、正しくフォーマットされます。注 (item.total は double/decimal です)

jQueryで正規表現も使用できる場合

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
于 2013-06-06T13:55:50.530 に答える
50

JQUERY FORMATCURRENCY プラグイン
http://code.google.com/p/jquery-formatcurrency/

于 2011-02-18T17:07:39.677 に答える
39

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}
于 2014-05-19T22:02:52.600 に答える
22

jQuery FormatCurrency プラグインが良い答えである理由の当然の帰結として、あなたのコメントに反論したいと思います。

1. code.google.com/p/jquery-formatcurrency - すべての文字を除外しません。単一の文字を入力できますが、それは削除されません。

はい、 formatCurrency() 自体は文字を除外しません:

// only formats currency
$(selector).formatCurrency();

しかし、formatCurrency プラグインに含まれる toNumber() はそうします。

したがって、次のことを行います。

// removes invalid characters, then formats currency
$(selector).toNumber().formatCurrency();
于 2012-03-12T19:41:40.980 に答える
10

以前は jquery 形式の通貨プラグインを使用していましたが、最近非常にバグが多くなりました。USD/CAD のフォーマットのみが必要なので、独自の自動フォーマットを作成しました。

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

            $(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
        });

入力を通貨としてフォーマットするクラスを設定するだけ<input type="text" class="currencyMask" />で、どのブラウザでも完全にフォーマットされます。

于 2016-06-01T21:20:11.223 に答える
4

jQuery (プラグインなし)で正規表現通貨を試してください:

$(document).ready(function(){
  $('#test').click(function() {
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);
    if (TESTCURRENCY.length <= 1) {
      $('#valueshow').val(
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))
      );
    } else {
      $('#valueshow').val('Invalid a value!');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" value="12345.67890" id="value">
<input type="button" id="test" value="CLICK">
<input type="text" value="" id="valueshow">

編集:値を有効/無効に新規チェック

于 2015-12-28T18:30:41.770 に答える