When calculating values within an Array I am getting this: total = "0212.16967.04". The correct total in this example is:1179.20
function calculateSum(){
//build array of numbers
amtArray = [];
$('.amount').each(function (index, value) {
amtArray.push($(this).text()||0);
});
//calculate all values and return results
var sum = sumArray(amtArray);
console.log('sum ->', sum)
}
function sumArray(input) {
var total = 0;
for (idx=0; idx <= input.length-1; idx++) {
total += input[idx];
}
return total;
}
calculateSum()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amount">212.16</div>
<div class="amount">967.04</div>
Should output: 1179.20
"212.16" + "967.04"on the developer console - it's string concatenation. Convert tonumberbefore using the+operator.$('.amount').each(function (index, value) { amtArray.push(parseFloat($(this).text())||0); });