Reputation: 1701
I am trying to add total of my data:
[{"sector": "Basic drinking water supply and basic sanitation", "budget": 558733.7, "no": 8},
{"sector": "Culture and recreation", "budget": 1550000.0, "no": 2},
{"sector": "Roads", "budget": 1221142.04, "no": 4},
{"sector": "Agriculture", "budget": "", "no": 1},
{"sector": "Health", "budget": "", "no": 4},
{"sector": "Education", "budget": 473379.58, "no": 6},
{"sector": "Energy generation & supply", "budget": 584624.55, "no": 1},
{"sector": "Agricultural water resources", "budget": 40000.0, "no": 1}]
so my code goes like this:
for(i=0;i<data.length;i++){
data[i]["budget"]= +data[i]["budget"];
console.log(+data[i]["budget"]);
end_val+= data[i]["budget"];
console.log(end_val);
}
but the output is concatenation of string. Why does javascript
not typecast my values to integer? i tried parseInt()
too.
Upvotes: 0
Views: 330
Reputation: 11
It would be much better if you use :---> Typecast.js
var sum = 0;
for (i=0 ; i<data.length ; i++){
var val = type.num.to(data[i]["budget"]);
sum += type.nan(val) ? 0 : val;//---->HERE You dont even need to do this validation
}
console.log(sum);
Typecast is distributed under the MIT licence
Upvotes: 1
Reputation: 14591
Initialize end_val variable to 0. Check whether both the operands are of type Number when you use increment operator for number addition.
var end_val = 0;
for(i=0;i<data.length;i++){
end_val+= parseFloat(data[i]["budget"]);
console.log(end_val);
}
Upvotes: 1
Reputation: 14640
You want to sum all the budget right?
You need to cast using parseFloat
and check whether the parsed value is a number or not using isNaN
.
var data = [
{"sector": "Basic drinking water supply and basic sanitation", "budget": 558733.7, "no": 8},
{"sector": "Culture and recreation", "budget": 1550000.0, "no": 2},
{"sector": "Roads", "budget": 1221142.04, "no": 4},
{"sector": "Agriculture", "budget": "", "no": 1},
{"sector": "Health", "budget": "", "no": 4},
{"sector": "Education", "budget": 473379.58, "no": 6},
{"sector": "Energy generation & supply", "budget": 584624.55, "no": 1},
{"sector": "Agricultural water resources", "budget": 40000.0, "no": 1}
];
var sum = 0;
for (i=0 ; i<data.length ; i++){
var val = parseFloat(data[i]["budget"]);
sum += isNaN(val) ? 0 : val;
}
console.log(sum);
Upvotes: 1
Reputation: 77778
Array.prototype.reduce should sum everything up easily
var sum = data.reduce(function(sum, row) {
return sum += Number(row.budget);
}, 0);
As for the string issue, that's happing because some rows have {budget: ""}
. When a string
is added to a float
in JavaScript, it becomes a string. Additional "additions" will be string concatenations.
Note: this requires ECMAScript >= 5
Upvotes: 1
Reputation: 2510
The problem is that some of your values are not integers.
Try using parseFloat()
Hope this helps.
Upvotes: 0