add to values separated by a comma [closed]

You changed it to an array. You can add to an array in javascript with .push();

var totalAmount = [55.99, 7.01];
console.log(totalAmount); // produces something like [55.99, 7.01, 5]

[edit] Yeah, the whole format of the question threw me off. If you’re wanting the SUM of an array of numbers, you can do so with a for loop:

var total = 0;
for (var i = 0; i < totalAmount.length; i++)
    total += parseFloat(totalAmount[i]);

total will have the sum of the array, and it work for any length array. If we didn’t have parseFloat, it might do some weird things since the concatenate and addition operators are both + in JavaScript. So we do parseFloat(totalAmount[i]) and that will make sure if even if you have a string like "55.55" in your array, it will be used as a number and not a string.

Browse More Popular Posts

Leave a Comment