Question

I am currently using this code to calculate the total from a column in a table:

function calculateTotals() {
//these will hold the totals
var hours = 0;

//reference the rows you want to add
//this will not include the header row
var rows = $("#deliverables tr:not(:first-child, :last-child)");
rows.children("td:nth-child(2)").each(function() {
    hours += parseInt($(this).html());
});

midHours = (hours).toFixed(2);

$(".total-hours").html(midHours);

};

However, the output midHours will not show decimals. For example a table cell with value 12.5 - outputs as 12 in the .total-hours cell.

Was it helpful?

Solution

because you are using parseInt(), use parseFloat() instead

var rows = $("#deliverables tr:not(:first-child, :last-child)");
rows.children("td:nth-child(2)").each(function() {
    hours += parseFloat($(this).html());
});

OTHER TIPS

Instead using parseInt, multiply your value with 1 (your_val * 1). It will convert a value into number.

hours += $(this).html() * 1;

What Arun said, but I offer an explanation, since you obviously don't know much about variables, an integer is a number without decimal places like 15 or 256 or 108,197; in parseInt(n), the int stands for integer, the float in parseFloat(n) stands for floating-point number

If you turn a float into an int, it simply drops everything after the decimal place without rounding, so 72.9999999999 would become 72. a quick fix is to add .499999999 and then convert to integer, but that's only if you actually wanted to convert to integer using rounding, and it sounds like you do not.

use parseFloat if you want decimal places

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top