Put Comma Values in Numbers

This function assumes what is being submitted to it is a string, with a decimal point and two places after the decimal. To get your number into that format first, use this.

Then this function will properly comma separate the number. For example, 2345643.00 will return 2,345,643.00

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

Comments

  1. dyllon
    Permalink to comment#

    is there something like this for PHP?

  2. Lokesh
    Permalink to comment#

    Ohhh.. Wonderful code snippet. Searching for long time.

  3. Jack

    this is how I do it:

    function addCommas(nStr)
    {
    nStr += ”;
    var x = nStr.split(‘.’);
    var x1 = x[0];
    var x2 = x.length > 1 ? ‘.’ + x[1] : ”;
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
    x1 = x1.replace(rgx, ‘$1’ + ‘,’ + ‘$2’);
    }
    return x1 + x2;
    }

    • John
      Permalink to comment#

      Jack you function is much better thx. The function from the post is riddled with errors.

  4. Zidu
    Permalink to comment#

    How about this script.
    Any chance to insert a comma or a space between the numbers in this counter?

    kasa=new Date(2008 ,12 ,60 ,30 ,01);
    setInterval(function(){
    with(Math){
    var w=floor(((new Date())-kasa)/1000),lr,dr,mr,
    l=floor(w/31536000),d=floor((lr=w%31536000)/86400),
    g=floor((dr=lr%86400)/3600),m=floor((mr=dr%3600)/60),
    s=floor(mr%60);
    document.getElementById(‘money’).innerHTML=
    (l?l+’ l., ‘:”)+d+’ dni,’+g+’ godz., ‘
    +m+’ min., ‘+s+’ sek.’;
    }
    },1000);
    setInterval(function(){
    document.getElementById(‘MoneyCounter’).innerHTML=
    ((new Date())-kasa);
    },130);

  5. Anonymous
    Permalink to comment#

    Here’s the same thing in 1 line. If anybody can do better, do share.

    function commas(str) {
        return str.replace(/.(?=(?:.{3})+$)/g, '$&,');
    }
  6. William Barath
    Permalink to comment#

    Can’t do better making it shorter, but I can fix it so it takes numeric arguments!

    function commas(str) {
    return (str+””).replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

  7. William Barath
    Permalink to comment#

    Hmm… and make it handle decimals in a hackish way. ;-)

    function commas(str) {return (str+””).replace(/.(?=(?:[0-9]{3})+\b)/g, ‘$&,’);

  8. maziar

    function format(input)
    {
    var num=input.value.replace(/[^\d]/g,”);
    if(num.length>3)
    num = num.replace(/\B(?=(?:\d{3})+(?!\d))/g, ‘-‘);
    input.value=num;
    }

  9. Gaurang Zalariya
    Permalink to comment#

    Hello Chris,

    If amount will be 2200 then your var “d” will give an error as undefined variable and script will not execute this script only work when your amount is 2200.00 so I have edited your script and used it in my website ;) below is revised code which might solve this issue.

    function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.',2)
    var d = a[1];
    var i = parseInt(a[0]);
    if(isNaN(i)) {
    return '';
    }
    var minus = '';
    if(i < 0) {
    minus = '-';
    }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3) {
    var nn = n.substr(n.length-3);
    a.unshift(nn);
    n = n.substr(0,n.length-3);
    }
    if(n.length > 0) {
    a.unshift(n);
    }
    n = a.join(delimiter);
    if(d) {
    if(d.length < 1) {
    amount = n;
    } else {
    amount = n + '.' + d;
    }
    } else {
    amount = n + ".00"
    }
    amount = minus + amount;
    return amount;
    }

  10. Yashar Imanlou
    Permalink to comment#

    God bless “.toLocaleString()”

  11. Sm0ove
    Permalink to comment#

    @Yashar Imanlou: unfortunately the method toLocaleString isn’t widely supported yet, see http://caniuse.com/#search=locale.

  12. Ujah
    Permalink to comment#

    I want to use it in html how can i add this
    document.getElementById(“demo”).innerHTML = commer();
    Or to use documen.wrte = “12,345”;

    I need to make something like this 12345 to 12,345

  13. Santi
  14. Wondering Willy
    Permalink to comment#

    This one seems the simplest / quickest…

    function commas(str) {
    return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

    But, don’t laugh please… I freely admit I’m not a programmer. Just trying to do a simple change on a page — adding commas. Been playing with this for 40 minutes and not getting it.

    I’m trying to get a variable I’ve calculated and use on the page (“calculatedHours”) to display with commas. Had NO clue it was this big of a deal…

    Anyway, explaining it like I’m a 6 year old… Where would I plug this into the function?

    I thought it would be:

    function commas(calculatedHours) {
    return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

    and then

    document.write(calculatedHours)

    But no…. what do I replace to get it to display the variable calculatedHours with the commas???

  15. Wondering Willy
    Permalink to comment#

    Man….this is frustrating. I’ve played with content (HTML) on my page before, and thought throwing in a few lines of Java wouldn’t be too tough. It’s crazy tough. I never would’ve taken it on – I outsource any design (etc), but the time it’s taken to make a simple page has been astounding.

    Still stuck. All I want to do is have it display a few numbers with commas for ease of reading. There’s a variable (a couple, actually, but I’m hoping if I get the method down I can repeat it).

    Here’s the section (I AM ADDING SPACES WITHIN THE WORD S C R I P T SO IT WILL DISPLAY HERE – THAT’S THE ONLY DIFFERENCE)

    < s c r i p t >
    document.write(“As of today, “)
    document.write(calculatedHours)
    document.write(” hours have passed…”)
    < / s c r i p t >

    It outputs:

    As of today, 3965 hours have passed…

    I want it to output:

    As of today, 3,965 hours have passed…

    IS THERE REALLY NO SIMPLE WAY TO DO SOMETHING THIS SEEMINGLY SIMPLE????

    Every piece of code I copy over doesn’t work… I’m sure there’s some “of course” stuff I’m missing, and the fault is mine for not knowing, but can anyone give me a few lines of code to accomplish this?

    Thanks

  16. Wondering Willy
    Permalink to comment#

    Can anyone take a quick crack at this?

    Still trying to do something that seems like it should be simple…

    I’ve calculated a variable (“calculatedHours”), trying to get it to display with commas.

    I thought it would be:

    function commas(calculatedHours) {
    return str.replace(/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

    and then

    document.write(calculatedHours)

    …. not working. Anyone see the problem / can anyone post a couple lines of code that would work?

    Thanks….

  17. NoLongerWondering
    Permalink to comment#

    Never mind.

    Here’s what works, for others who may come across this page / question:

    <

    script type=”text/javascript”>

    function numberWithCommas(x) { // Zamaria
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
    }

    document.write(numberWithCommas(calculatedHours))

  18. Daniel
    Permalink to comment#

    I use this function to generate a constantly increasing number within a div element. http://jsfiddle.net/obysrnm2/

    Does anyone have any suggestions for combining the generator with the separator. My implementations seem to return with error.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```

We have a pretty good* newsletter.