开发者

Add thousands separator to auto sum

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).replac开发者_JAVA技巧e(',', ''));

}


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.)


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)));

}


function DigitsFormat(str) {
        return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}


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(',');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜