简体   繁体   中英

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(',', ''));
    });

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, ''));

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 US English, but you can optionally specify a different locale if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM