Skip to content

Instantly share code, notes, and snippets.

@tborychowski
Created March 6, 2012 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tborychowski/1989135 to your computer and use it in GitHub Desktop.
Save tborychowski/1989135 to your computer and use it in GitHub Desktop.
JS :: Format a number
/**
* Formats numbers (or string numbers)
* @param number int or int-parsable string
* @param prec decimal precision
* @returns formatted number as string
*/
numberFormat : function (number, prec) {
var ext, name, numS, rgx = /(\d+)(\d{3})/;
number = number || '0';
prec = prec || 0;
numS = ('' + number).split('.');
name = numS[0];
ext = numS[1];
if (prec > 0) ext = ((ext || '') + new Array(prec + 1).join('0')).substr(0, prec);
else ext = '';
while (rgx.test(name)) name = name.replace(rgx, '$1' + ',' + '$2');
return name + (ext ? '.' + ext : '');
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment