Format number with commas every 3 decimal places


/ Published in: JavaScript
Save to your folder(s)

Adds commas to numbers.
1234567 becomes 1,234,567


Copy this code and paste it in your HTML
  1. function add_commas(nStr)
  2. {
  3. nStr += '';
  4. x = nStr.split('.');
  5. x1 = x[0];
  6. x2 = x.length > 1 ? '.' + x[1] : '';
  7. var rgx = /(\d+)(\d{3})/;
  8. while (rgx.test(x1)) {
  9. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  10. }
  11. return x1 + x2;
  12. }

URL: http://www.mredkj.com/javascript/nfbasic.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.