Add thousands separator to auto sum

筅森魡賤 提交于 2019-12-21 06:10:50

问题


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

}

回答1:


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




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

}



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/6502333/add-thousands-separator-to-auto-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!