Skip to main content

Posts

Showing posts from October, 2008

Adding commas to numbers with JavaScript

I recently went to add commas to a number on entry. Found a nice script here. Only thing I changed was to make it set the value in the function. I also liked his solution for adding separators other than commas.The code:function addCommas(obj) { nStr = obj.value; 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'); } obj.value = x1 + x2; }