2

I would like the sum calculated from the script below to display two decimals, and thousands separated by a comma. At this stage it only display the two decimals. I am new to programming and have tried various techniques but could not solve the problem. Below my JS 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(',', ''));

}
Charles
  • 50,943
  • 13
  • 104
  • 142
Pitt
  • 21
  • 1
  • 2
  • And here is where it display the result: 0 – Pitt Jun 28 '11 at 06:16
  • 1
    possible duplicate of [Add comma to numbers every three digits using jQuery](http://stackoverflow.com/questions/1990512/add-comma-to-numbers-every-three-digits-using-jquery) – kapa Jun 28 '11 at 06:26

4 Answers4

4
sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,')

Explanation:

Find 1-to-3 digits at the start of the string, followed by at least one trio of digits, followed by a decimal point or the end of the number (so the same regular expressions works for whole numbers as well as numbers with 2 decimal places.)

searlea
  • 8,173
  • 4
  • 34
  • 37
2

You need to use something like this:

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

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(addCommas(sum.toFixed(2)));

}
Eugene Manuilov
  • 4,271
  • 8
  • 32
  • 48
2
function DigitsFormat(str) {
        return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}
Sergey
  • 37
  • 6
0

Here's a non-regular expression way of adding thousands separators to the integer part:

function doThousands(n) {
  n = '' + n;
  if (n.length < 4) return n;
  var c = n.length % 3;
  var pre = n.substring(0, c);
  return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
RobG
  • 142,382
  • 31
  • 172
  • 209