I have an HTML table that I want to add a total of the price column.
I have done this with javascript, however, I'm having an issue where it's not adding the value after a decimal point e.g. 5.50
here is my js code
var tds = document.getElementById('quote').getElementsByClassName('tprice');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
var total = sum.toFixed(2);
document.getElementById('totalprice').innerHTML += "£" + total;
Your script can benefit from a map and a reduce with casting to number rather than the parseInt you have which will remove all decimals
I use the unary plus here instead of parseInt/Float
let sum = 0;
const prices = [...document.querySelectorAll('#quote .tprice')]
.map(td => isNaN(td.textContent) ? 0 : +td.textContent); // an array of numbers
if (prices.length) sum = prices.reduce((a, b) => a + b); // reduced to a sum
document.getElementById('totalprice').innerHTML += "£" + sum.toFixed(2);
<table id="quote">
<tr>
<td class="tprice">15.50</td>
</tr>
<tr>
<td class="tprice">16.50</td>
</tr>
<tr>
<td class="tprice">17.50</td>
</tr>
<tr>
<td class="tprice">18.50</td>
</tr>
</table>
<span id="totalprice"></span>
Maybee try change this line:
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
to
var value = parseFloat(tds[i].innerHTML);
sum += isNaN(value) ? 0 : value;
but better show example of HTML table with sample (NOT PRODUCTION!) data