Skip to content

Instantly share code, notes, and snippets.

@demian85
Created July 12, 2012 16:06
Show Gist options
  • Save demian85/3099066 to your computer and use it in GitHub Desktop.
Save demian85/3099066 to your computer and use it in GitHub Desktop.
JS number format func
function numberFormat(number, dec, dsep, tsep) {
if (isNaN(number)) return "";
number = number.toFixed(dec || 0);
var pindex = number.indexOf('.'), fnums, decimals, parts = [];
if (pindex > -1) {
fnums = number.substring(0, pindex).split('');
decimals = (dsep || '.') + number.substr(pindex+1);
}
else {
fnums = number.split('');
decimals = '';
}
do {
parts.unshift(fnums.splice(-3, 3).join(''));
} while (fnums.length);
return parts.join(tsep || ',') + decimals;
}
// test...
var nums = {
"numberFormat2(90000)" : numberFormat2(90000),
"numberFormat2(90000, 2)" : numberFormat2(90000, 2),
"numberFormat2(1000.754)" : numberFormat2(1000.754),
"numberFormat2(1000.754, 2)" : numberFormat2(1000.754, 2),
"numberFormat2(1000.754, 0, ',', '.')" : numberFormat2(1000.754, 0, ',', '.'),
"numberFormat2(1000.754, 2, ',', '.')" : numberFormat2(1000.754, 2, ',', '.'),
"numberFormat2(1000000000)" : numberFormat2(1000000000),
"numberFormat2(1000000000.987654, 2)" : numberFormat2(1000000000.987654, 2)
}
Object.keys(nums).forEach(function(k) {
console.log(k + ' ' + nums[k]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment