Reputation: 61
I'm trying to add the following but it keeps concatenating and returning a string.
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += parseFloat(i).toFixed(2);
});
Yes, I need it to return / add it with the decimals. Unsure what to do
Upvotes: 5
Views: 1324
Reputation: 36511
If you wanted a more functional approach, you could also use Array.reduce
:
var nums = [1.99, 5.11, 2.99];
var sum = nums.reduce(function(prev, cur) {
return prev + cur;
}, 0);
The last parameter 0
, is an optional starting value.
Upvotes: 7
Reputation: 8513
Try reduce, a recursive option:
function sum(inputNums) {
var nums = inputNums;
var total = nums.reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
});
alert('' + total);
}
sum([1.99, 5.11, 2.99]);
Upvotes: 1
Reputation: 850
If you aren't storing strings of floats, you don't need to use parseFloat(i), that parses a float from a string. You could rewrite this as:
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += i;
});
var fixed = total.toFixed(2);
console.log(fixed);
or
var nums = [1.99, 5.11, 2.99];
var total = 0;
for(var i = 0; i < nums.length; i++){
total += nums[i];
}
var fixed = total.toFixed(2);
console.log(fixed);
Upvotes: 4
Reputation: 695
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += parseFloat(i);
});
alert(total.toFixed(2));
Yes, it with the decimals
Upvotes: 1