使用Javascript或jQuery向总数添加千位分隔符? [英] Add a thousands separator to a total with Javascript or jQuery?

查看:566
本文介绍了使用Javascript或jQuery向总数添加千位分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对html表中的数据列求和的函数.它如此令人钦佩,只有我想让它放在逗号之间,以分隔成千上万个逗号.最初,您会注意到,要添加的数字中有逗号.这样函数将添加它们,将它们删除.如何在其中添加逗号?

I have a function that sums a column of data in an html table. It does so admirably only I would like to have it put the commas in there that are needed to separate the thousands. Initially, you'll note, there are commas in the numbers being added. So that the function will add them, they are removed. How do I add the commas back in there?

<script type="text/javascript">
    function sumOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;
        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
          .children("td:nth-child(" + columnIndex + ")")
          .each(function() {
              tot += parseInt($(this).html().replace(',', ''));
          });
        return "Total Pounds Entered : " + tot;
    }
</script>

推荐答案

$(this).html().replace(',', '')实际上不应修改页面.您确定在页面中删除了逗号吗?

The $(this).html().replace(',', '') shouldn't actually modify the page. Are you sure the commas are being removed in the page?

如果是,此 addCommas函数应该可以解决问题.

If it is, this addCommas function should do the trick.

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

这篇关于使用Javascript或jQuery向总数添加千位分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆