jQuery: How do I sum a column of numbers with commas?

Deadly 提交于 2021-02-04 21:35:00

问题


I used the following function I found online and it works perfectly. However, when my user later asked for commas to be included in the numbers, it broke. It only adds the numbers preceding the comma.

Here is the function:

function sumOfColumns(tableID, columnIndex, hasHeader) {
            var tot = 0;
            $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
              .children("td:nth-child(" + columnIndex + ")")
              .each(function() {
                  tot += parseInt($(this).html());
              });

Do I need to stop the 'parseInt' piece?


回答1:


I'm assuming that you mean that the numbers now have commas as a thousands-separator, like this:

1234567 = "1,234,567"

You can remove all of those commas before you call parseInt, like this:

tot += parseInt($(this).html().replace(',',''));


来源:https://stackoverflow.com/questions/2456195/jquery-how-do-i-sum-a-column-of-numbers-with-commas

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