Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript addition / sum loop

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

like image 428
user44754 Avatar asked May 21 '15 05:05

user44754


People also ask

How do I sum a loop in JavaScript?

Example 1: Sum of Natural Numbers Using for LoopThe parseInt() converts the numeric string value to an integer value. The for loop is used to find the sum of natural numbers up to the number provided by the user. The value of sum is 0 initially. Then, a for loop is used to iterate from i = 1 to 100 .

How do you define a number in JavaScript?

In JavaScript, numbers are primitive data types. For example, const a = 3; const b = 3.13; Unlike in some other programming languages, you don't have to specifically declare for integer or floating values using int, float, etc.

How do you add numbers to an array in a for loop?

Here is the simple code: int i, arr[5]; for(i=1; i<5; i++){ printf("%d ", arr[i]); c.


2 Answers

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.

like image 57
Rob M. Avatar answered Sep 30 '22 01:09

Rob M.


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);
like image 23
Andrew Malta Avatar answered Sep 30 '22 01:09

Andrew Malta