0

次のjQueryプラグインを使用して、数値にコンマを自動的に追加しています。問題は、小数($ 1,000.00など)を入力すると、$ 1,000、.00に変更されることです。

小数点とその後の文字を無視するように正規表現を更新するにはどうすればよいですか?

String.prototype.commas = function() {
    return this.replace(/(.)(?=(.{3})+$)/g,"$1,");
};

$.fn.insertCommas = function () {
    return this.each(function () {
        var $this = $(this);

        $this.val($this.val().replace(/(,| )/g,'').commas());
    });
};
4

3 に答える 3

1

簡単な修正のようです。.{3}(任意の3文字)を[^.]{3}(ピリオド以外の任意の3文字)に変更するだけです

String.prototype.commas = function() {
    return this.replace(/(.)(?=([^.]{3})+$)/g,"$1,");
};

編集:

またはそれ以上:

String.prototype.commas = function() {
    return this.replace(/(\d)(?=([^.]{3})+($|[.]))/g,"$1,");
};
于 2011-12-28T20:39:38.840 に答える
1

StackOverflowですでに優れた答えがあります:JavaScriptで数値をお金としてフォーマットするにはどうすればよいですか?

Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

これがデモです:http://jsfiddle.net/H4KLD/

于 2011-12-28T20:45:52.737 に答える
1

.これは、 :の後に3桁以内である限り機能するはずです。

replace(/(\d)(?=(?:\d{3})+(?:$|\.))/g, "$1,");
于 2011-12-28T20:48:36.903 に答える