We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

section31 on 08/13/07


Tagged


Versions (?)


Who likes this?

3 people have marked this snippet as a favorite

maid450
eskimoblood
jdstraughan


Mootools - numberFormat


Published in: JavaScript 


Format a number with grouped thousands

  1. Number.extend({
  2.  
  3. /*
  4. Property: numberFormat
  5. Format a number with grouped thousands.
  6.  
  7. Arguments:
  8. decimals, optional - integer, number of decimal percision; default, 2
  9. dec_point, optional - string, decimal point notation; default, '.'
  10. thousands_sep, optional - string, grouped thousands notation; default, ','
  11.  
  12. Returns:
  13. a formatted version of number.
  14.  
  15. Example:
  16. >(36432.556).numberFormat() // returns 36,432.56
  17. >(36432.556).numberFormat(2, '.', ',') // returns 36,432.56
  18. */
  19.  
  20. numberFormat : function(decimals, dec_point, thousands_sep) {
  21. decimals = Math.abs(decimals) + 1 ? decimals : 2;
  22. dec_point = dec_point || '.';
  23. thousands_sep = thousands_sep || ',';
  24.  
  25. var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals
  26. var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
  27. return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) +
  28. (decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
  29. }
  30.  
  31.  
  32. });

Report this snippet 

You need to login to post a comment.