Posted By

uberdragon on 09/21/13


Tagged

number format comma


Versions (?)

Add commas to numbers


 / Published in: JavaScript
 

A quick function that makes it easy to convert an integer into a number string with commas inserted.

  1. function number_with_commas(n){
  2. var m = Math.abs(n);
  3. var sign = n < 0 ? '-' : '';
  4. var output = "";
  5. var chars = String(m).split('').reverse();
  6. var commas = Math.floor((chars.length-1) / 3);
  7. var i = 0;
  8. for(i=0; i<commas; i++){
  9. output = output + chars.slice(0,3).join('') + ',';
  10. chars = chars.slice(3);
  11. }
  12. output = output + chars.join('');
  13. return sign + output.split('').reverse().join('');
  14. }

Report this snippet  

You need to login to post a comment.