Iladarsda
Iladarsda

Reputation: 10692

JavaScript sum the number in the array

I have a following array var total = [10, 0.25, 12.75, 1, 0];

When I do:

 for (var i= 0; i< total.length; i++) {
      totalNo += parseInt(+(total[i]));
 }

The totalNo is always a full number. Looks like the .XX after dot value is skipped. How to make sure it is added properly?

Upvotes: 1

Views: 239

Answers (3)

spaceman12
spaceman12

Reputation: 1109

You dont need either parseInt or parseFloat here. If speed is concerned and for large arrays, used the native loop, it is much faster! however care be be taken as how you code it -

var total = [10, 0.25, 12.75, 1, 0],totalNo=0;
var len=total.length;
for(var i= 0; i<len; i++) 
{
    totalNo = totalNo+total[i];
}

Always note that totalNo+=total[i] is slower than totalNo+total[i]

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123417

use parseFloat() instead of parseInt() to preserve decimal part

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

Note1: no need to write +(total[i])
Note2: as pointed out by Utkanos, if your array values contain only floating-point values, then parseFloat is not even necessary

Upvotes: 4

Mitya
Mitya

Reputation: 34596

You shouldn't need to run any numeric coercion function (e.g. parseInt) - your array values are already numbers.

If an ECMA5 solution is acceptable, you can use reduce():

var arr = [10, 0.25, 12.75, 1, 0];
alert(arr.reduce(function(curr_total, val) {
    return curr_total + val;
}, 0)); //24

Upvotes: 4

Related Questions