Skip to content

Instantly share code, notes, and snippets.

@coolreader18
Last active January 26, 2018 14:59
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 coolreader18/9e07061958656cf14bb9b465f895569f to your computer and use it in GitHub Desktop.
Save coolreader18/9e07061958656cf14bb9b465f895569f to your computer and use it in GitHub Desktop.
Properly separate a large number.
/**
* Separate a large number into commas
* @param {Number} num The number to split up
* @param {Object|String} opts Options, for now it's just joiner is the possible joiner, if you'd like to use dots instead of commas or something.
* @example
* commas(12345678) // returns 12,345,678
* @example
* commas(211409200504011, {joiner:"."}) // returns 211.409.200.504.011
*/
function commas(num, opts) {
var arr = Array.from(num.toString()).reverse(),
copy = arr.slice(),
end = [];
for (var i = 0;i<arr.length;i++) {
if (i%3==0) {
end.push(copy.splice(0, 3).reverse().join(""))
}
if (i==arr.length) {
end.push(arr.reverse().join(""))
}
}
return end.reverse().join((opts ? opts.joiner : null) || ",");
}
try{export default commas;}catch(e){try{module.exports=commas}catch(r){}};
{
"name": "commas",
"version": "1.0.0",
"author": "coolreader18",
"main": "commas.js",
"repository": "gist:coolreader18/9e07061958656cf14bb9b465f895569f",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment