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. User Avatar
    dyllon
    Permalink to comment#

    is there something like this for PHP?

  2. User Avatar
    Lokesh
    Permalink to comment#

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

  3. User Avatar
    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;
    }

    • User Avatar
      John
      Permalink to comment#

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

  4. User Avatar
    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. User Avatar
    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(https://cdn.css-tricks.com/.(?=(?:.{3})+$)/g, '$&,');
    }
  6. User Avatar
    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(https://cdn.css-tricks.com/.(?=(?:.{3})+$)/g, ‘$&,’);
    }

  7. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    Yashar Imanlou
    Permalink to comment#

    God bless “.toLocaleString()”

  11. User Avatar
    Sm0ove
    Permalink to comment#

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

  12. User Avatar
    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. User Avatar
    Santi
  14. User Avatar
    Wondering Willy
    Permalink to comment#

    This one seems the simplest / quickest…

    function commas(str) {
    return str.replace(https://cdn.css-tricks.com/.(?=(?:.{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(https://cdn.css-tricks.com/.(?=(?:.{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. User Avatar
    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. User Avatar
    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(https://cdn.css-tricks.com/.(?=(?:.{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. User Avatar
    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. User Avatar
    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.

  19. User Avatar
    Elad Karako

    **sign**… N00bs…

    String(1234567890).replace(/(\d)(?=(\d{3})+$)/g, "$1,")
    

    "1,234,567,890"

  20. User Avatar
    Dalibor Sojic
    Permalink to comment#

    All of this is wrong concept. In general, programmer/developer should not “format” the numbers.

    The right concept:
    Client side (browser), should read “regional settings” from the OS, and format the numbers according that. This should happens primary in “input” fields as well as in inline text wrapped with some tag.

    Ex: <number>123456</number> => 123.456
    <number decimals="2">123456789E-4</number> => 12.345,68

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag