Created
March 6, 2012 21:47
-
-
Save tborychowski/1989135 to your computer and use it in GitHub Desktop.
JS :: Format a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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