Skip to content

Instantly share code, notes, and snippets.

@ripter
Created August 27, 2012 23:44
Show Gist options
  • Save ripter/3493456 to your computer and use it in GitHub Desktop.
Save ripter/3493456 to your computer and use it in GitHub Desktop.
Number formatter
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