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?
3 Answers 3
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
10 Comments
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
2 Comments
+total[i] instead of any parsing function. Let's remember that parseFloat("10px") === 10, and maybe that's not what we want.parseFloat coerces to a Number.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]