Mootools - numberFormat


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

Format a number with grouped thousands


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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.