Put Comma Values in Numbers


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

This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.

Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00


Copy this code and paste it in your HTML
  1. function CommaFormatted(amount) {
  2. var delimiter = ","; // replace comma if desired
  3. var a = amount.split('.',2)
  4. var d = a[1];
  5. var i = parseInt(a[0]);
  6. if(isNaN(i)) { return ''; }
  7. var minus = '';
  8. if(i < 0) { minus = '-'; }
  9. i = Math.abs(i);
  10. var n = new String(i);
  11. var a = [];
  12. while(n.length > 3) {
  13. var nn = n.substr(n.length-3);
  14. a.unshift(nn);
  15. n = n.substr(0,n.length-3);
  16. }
  17. if(n.length > 0) { a.unshift(n); }
  18. n = a.join(delimiter);
  19. if(d.length < 1) { amount = n; }
  20. else { amount = n + '.' + d; }
  21. amount = minus + amount;
  22. return amount;
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.