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