JavaScript Add / Sum Offset

I am trying to add the following, but it continues to concatenate and return 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 decimal places. Not sure what to do

+5
source share
4 answers

If you need a more functional approach, you can 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.

+7
source

If you do not store strings of floats, you do not need to use parseFloat (i), which parses the float from the string. You can 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); 
+4
source
 var nums = [1.99, 5.11, 2.99]; var total = 0; nums.forEach(function(i) { total += parseFloat(i); }); alert(total.toFixed(2)); 

Yes it is with decimal places

+1
source

Try reducing the 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]); 
+1
source

All Articles