Format numbers w/ commas


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



Copy this code and paste it in your HTML
  1. function formatNumber(num, prefix){
  2. prefix = prefix || '';
  3. num += '';
  4. var splitStr = num.split('.');
  5. var splitLeft = splitStr[0];
  6. var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
  7. var regx = /(\d+)(\d{3})/;
  8. while (regx.test(splitLeft)) {
  9. splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
  10. }
  11. return prefix + splitLeft + splitRight;
  12. }
  13.  
  14. function unformatNumber(num) {
  15. return num.replace(/([^0-9\.\-])/g,'')*1;
  16. }
  17.  
  18.  
  19. //Usage:
  20. var test1 = formatNumber('5123456789.25'); // returns 5,123,456,789.25
  21. var test2 = formatNumber(1234.15,'$'); // returns $1,234.15
  22. var test3 = unformatNumber('$1,234.15'); // returns 1234.15

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.