Splits numbers with commas to make them more readable. Thanks to @maettig for being awesome
-
-
Save williammalo/2363615 to your computer and use it in GitHub Desktop.
number splitter
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(n){ | |
return //return | |
(""+n) //the number converted to a sting | |
.replace(/\B(?=(...)+$)/g,",") //with a comma inserted every 3 characters | |
} |
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
//simple version: | |
function(n){return(""+n).replace(/\B(?=(...)+$)/g,",")} | |
//Does not fuck decimals up version: | |
function f(a,b,c){return b||(c?a+',':a+'').replace(/(\.\d*)|\d(?=(\d{3})+\b)/g,f)} |
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": "numSplit", | |
"description": "Splits numbers with commas to make them more readable.", | |
"keywords": [ | |
"number", | |
"comma", | |
"math", | |
"format" | |
] | |
} |
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
<script> | |
numSplit = function(n){return(""+n).replace(/\B(?=(...)+$)/g,",")} | |
document.write(numSplit(3255325235523632)) | |
</script> |
You are right. I missed that in my tests. What about this?
function(a){return(''+a).replace(/\.\d*|\B(?=(\d{3})+\b)/g,function(a){return a||','})}
Merging the two functions is possible but makes the code very ugly. Edit: OK, here it is. This is smaller and more reliable because it does not insert a comma in "U100".
function f(a,b,c){return b?b:c?a+',':(''+a).replace(/(\.\d*)|\d(?=(\d{3})+\b)/g,f)}
@maettig
Sweet!
1 byte smaller:
function f(a,b,c){return b||(c?a+',':a+'').replace(/(\.\d*)|\d(?=(\d{3})+\b)/g,f)}
Yep, that's cool. This will start recursive calls of replace
but it will stop immediately because a
contains single digits only. When you do a benchmark you will see it's slower but this can be ignored because of the fast regular expression engines nowadays.
I like it!
What about saving 2 bytes with split?
function(n){return''+(''+n).split(/\B(?=(?:...)+$)/)}
123456789..toLocaleString() seems doing the trick.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
try numSplit(125252.2421415) in Firefox => "1252,52.242,141,5"
Correct would be 125,252.2421415