user1760710
user1760710

Reputation:

Jquery adding commas to numbers

I have textbox that contains numbers, everytime I add in digits it formats my number adding commas "onblur" event which works fine. But when I add in a digit when the number its already formatted the commas are not in the right place and at times adds in a zero.If I add in 1000000 its formats 1,000,000 but if I add or edit 1,000,0002 its end result is 1,000,0,002.

JQUERY

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

$("#mytextbox").blur(function(){
        this.value = addCommas(this.value.replace(',', ''));
    });

Upvotes: 1

Views: 1366

Answers (2)

adamSrgnt
adamSrgnt

Reputation: 60

I suggest using toLocaleString(). You can turn your entire addCommas function into one line:

parseInt(nStr.replace(/\D/g, '')).toLocaleString();

Let me break down what's happening here. First we're removing all non-digit characters from nStr by replacing them with ''. This is a little more thorough than just stripping out commas. Next, we're turning the string of digits into a Number using parseInt(). This will allow us to use some built in formatting methods in the Number prototype. Finally, the Number prototype has a function toLocaleString() that returns a string with a language sensitive representation of the number. The default is U.S. English, but you can optionally specify a different locale if you want.

Upvotes: 0

Roy
Roy

Reputation: 1967

replace(',', '') only replaces first comma to to empty. You need a global comma replace. Try changing this line

this.value = addCommas(this.value.replace(',', ''));

To this:

this.value = addCommas(this.value.replace(/,/g, ''));

Upvotes: 1

Related Questions