www.webdeveloper.com
Results 1 to 3 of 3

Thread: Add thousands separator to auto sum

  1. #1
    Join Date
    Jun 2011
    Posts
    2

    Add thousands separator to auto sum

    Hi there,

    I use JS to sum values from entries made by a user on a form.
    Then JS return the value with two decimals. However, I would like it to be separated every 1,000.00 with a comma. I am new to programming and have tried several methods. This is my code so far:

    function calculateSum() {

    var sum = 0;
    //iterate through each textboxes and add the values
    $(".txt").each(function() {

    //add only if the value is number
    if(!isNaN(this.value) && this.value.length!=0) {
    sum += parseFloat(this.value);
    }

    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#sum").html(sum.toFixed(2).replace(',', ''));

    }

    <span style="color: #f00;" id="sum">0</span>

  2. #2
    Join Date
    Feb 2006
    Posts
    2,927
    Code:
    function addCommas(n){
        var rx=  /(\d+)(\d{3})/;
        return String(n).replace(/^\d+/, function(w){
            while(rx.test(w)){
                w= w.replace(rx, '$1,$2');
            }
            return w;
        });
    }
    /* Don't add commas until you complete the additions- commas as thousands separators are for strings of digits, not numbers. */
    addCommas(123456789.75)
    // returned value: (String) 123,456,789.75
    Last edited by mrhoo; 06-28-2011 at 09:55 AM.

  3. #3
    Join Date
    Jun 2011
    Posts
    2
    Quote Originally Posted by mrhoo View Post
    Code:
    function addCommas(n){
        var rx=  /(\d+)(\d{3})/;
        return String(n).replace(/^\d+/, function(w){
            while(rx.test(w)){
                w= w.replace(rx, '$1,$2');
            }
            return w;
        });
    }
    /* Don't add commas until you complete the additions- commas as thousands separators are for strings of digits, not numbers. */
    addCommas(123456789.75)
    // returned value: (String) 123,456,789.75
    Thank you mrhoo,

    However, how do I apply the addCommas function to my sum value which should be displayed in the <span>?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles