Adding commas to numbers in Javascript for better readability

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; }

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *