0

I'm using the following jQuery plug-in to automatically add commas to a number. The problem is, when a decimal amount (like $1,000.00) is entered, it's changing it to $1,000,.00.

How can the regex be updated to ignore the decimal point and any characters after it?

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());
    });
};
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zoolander
  • 2,293
  • 5
  • 27
  • 37
  • possible duplicate of [How can I format numbers as money in JavaScript?](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – Jasper Dec 28 '11 at 20:54

3 Answers3

1

seems like a simple fix. Just change the .{3} (any three characters) to [^.]{3} (any non-period three characters)

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

EDIT:

or better yet:

String.prototype.commas = function() {
    return this.replace(/(\d)(?=([^.]{3})+($|[.]))/g,"$1,");
};
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • Thanks for the response. Unfortunately, after I made the change the comma doesn't show up when adding a number with a decimal and two zeros. Any ideas? – Zoolander Dec 28 '11 at 20:47
1

Here is an excellent answer already on StackOverflow: How can I format numbers as money in 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) : "");
 };

Here is a demo: http://jsfiddle.net/H4KLD/

Community
  • 1
  • 1
Jasper
  • 75,717
  • 14
  • 151
  • 146
1

This should work as long as there are no more than 3 digits after the .:

replace(/(\d)(?=(?:\d{3})+(?:$|\.))/g, "$1,");
Qtax
  • 33,241
  • 9
  • 83
  • 121