Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 3, 2015 01:37
Show Gist options
  • Select an option

  • Save williammalo/2363615 to your computer and use it in GitHub Desktop.

Select an option

Save williammalo/2363615 to your computer and use it in GitHub Desktop.
number splitter

Splits numbers with commas to make them more readable. Thanks to @maettig for being awesome

function(n){
return //return
(""+n) //the number converted to a sting
.replace(/\B(?=(...)+$)/g,",") //with a comma inserted every 3 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)}
{
"name": "numSplit",
"description": "Splits numbers with commas to make them more readable.",
"keywords": [
"number",
"comma",
"math",
"format"
]
}
<script>
numSplit = function(n){return(""+n).replace(/\B(?=(...)+$)/g,",")}
document.write(numSplit(3255325235523632))​​​​​
</script>
@maettig

maettig commented Apr 12, 2012

Copy link
Copy Markdown

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.

@atk

atk commented Apr 13, 2012

Copy link
Copy Markdown

I like it!

@tsaniel

tsaniel commented Jan 20, 2013

Copy link
Copy Markdown

What about saving 2 bytes with split?

function(n){return''+(''+n).split(/\B(?=(?:...)+$)/)}

@tsaniel

tsaniel commented Jan 22, 2013

Copy link
Copy Markdown

123456789..toLocaleString() seems doing the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment