Posted By

agarcim on 02/20/13


Tagged

javascript format numbers


Versions (?)

Format number


 / Published in: JavaScript
 

URL: http://www.anieto2k.com/2007/03/09/10-utilidades-javascript-que-deberias-conocer/

Format a number adding thousands separator and unformat the result of the formatting. The number can be rounded up the specified decimal places.

It uses ',' as decimal separator and '.' as thousand separator.

  1. //Deshace el formato creado por fmtNum
  2. String.desFmtNum = function(num) {
  3. return num.replace(/([^0-9,\-])/g,'').replace(/,/g,'.')*1;
  4. };
  5. //Formatea un número con '.' como separador de miles y ',' como separador decimal.
  6. Number.fmtNum = function(num,numDecs){
  7. if (typeof(num) == 'string')
  8. num = desFmtNum(num);
  9. if (numDecs) num = num.toFixed(numDecs);
  10. num += '';
  11. var splitStr = num.split('.');
  12. var splitLeft = splitStr[0];
  13. var splitRight = splitStr.length > 1 ? ',' + splitStr[1] : '';
  14. var regx = /(\d+)(\d{3})/;
  15. while (regx.test(splitLeft)) {
  16. splitLeft = splitLeft.replace(regx, '$1' + '.' + '$2');
  17. }
  18. if (numDecs>0)
  19. return splitLeft + splitRight;
  20. else
  21. return splitLeft;
  22. };

Report this snippet  

You need to login to post a comment.