Posted By

johnloy on 04/16/09


Tagged

javascript strings utility


Versions (?)

commafy a number in javascript


 / Published in: JavaScript
 

  1. // function commafyNumber - Adds commas to a
  2. // non-commaed number. For instance,
  3. // 1000000 becomes 1,000,000.
  4. // I did not write this original function: it comes
  5. // from Steve Levithan's blog:
  6. // http://blog.stevenlevithan.com/archives/commafy-numbers
  7. // (...but it's too useful not to snip)
  8.  
  9.  
  10. function commafyNumber(number) {
  11. var withcommas;
  12. withcommas = number.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
  13. var inter;
  14. inter = $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
  15. return inter;
  16. });
  17. return withcommas;
  18. }

Report this snippet  

You need to login to post a comment.