Question

There are ton of solution in Stackoverflow to calculate the totals of a column. That part I already solved. The issue is that of a total of 13 columns, only two are actually decimal numbers.This table get the data using ajax/datatables jQuery plugin (I don't know if the info is necessary but just in case).

enter image description here

If you look at the columns, the correct calculation should be 3113.27, but it rounds the number to 3111, so it is not taking into consideration the decimals.This is the code I'm using.

$("#example tr:last td:not(:first,:last)").text(function(i){
var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i+2)+")").each(function(){
    t += parseInt($(this).text(), 10 || 0);
});
return t;
});

Again, the rest of the columns are fine, because I just need to count/sum, but these two are causeing me trouble. Thanks for any help.

Was it helpful?

Solution

parseInt() returns an integer (i.e. no decimals). If you use parseFloat() it should work fine.

OTHER TIPS

Try this:

$("#example tr:last td:not(:first,:last)").text(function(i) {
  var t = 0;
  $(this).parent().prevAll().find("td:nth-child("+(i+2)+")").each(function(){
    t += parseFloat(this.innerText) || 0;
  });

  return t.toFixed(2);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top