Last active
January 26, 2018 14:59
-
-
Save coolreader18/9e07061958656cf14bb9b465f895569f to your computer and use it in GitHub Desktop.
Properly separate a large 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
/** | |
* 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){}}; |
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
{ | |
"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