It seems like a lot of code and work to just show “1532” as “1,532” but that’s Javascript for you. Clean and basic, but you seem to have to build so much from scratch. Of course, there are great libraries like JQuery and Dojo, but in case you want to write something fast — just use this code to call on the function to convert the simple number without commas into a more readable number with commas. Great for displaying dollar amounts. I don’t know about you, but the more commas the better (unless you’re looking a bill, of course.)
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; }