Add commas to numbers


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

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.