Hi Guys!
I was looking for a Javascript function to format numbers by adding commas for thousands etc. I want the function to run onBlur (i.e. when a user navigates away from a form input). The below function works, except if the user enters for example 1000000 and then navigates away from the form input and then goes back and adds an extra 0.
Does this make sense? Can anyone propose a fix?
Thanks!
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;
}