Created
August 27, 2012 23:44
-
-
Save ripter/3493456 to your computer and use it in GitHub Desktop.
Number formatter
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
function formatNumber(num) { | |
var thousands = ','; | |
var decimal = '.'; | |
var numStr = '' + num; | |
var formatted = ''; | |
if (typeof num !== 'number') { | |
throw new Error('Must pass a number, received "' + num + '" instead.'); | |
} | |
// is there a decimal point? | |
if ((0 | num) - num !== 0) { | |
formatted = decimal + numStr.substring(numStr.indexOf('.')+1); | |
numStr = numStr.substring(0, numStr.indexOf('.')); | |
} | |
// every 3 digits, add the seprator | |
while (numStr.length > 3) { | |
formatted = thousands + numStr.substr(-3) + formatted; | |
numStr = numStr.substring(0, numStr.length - 3); | |
} | |
// add anything left | |
formatted = numStr + formatted; | |
return formatted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment