Reputation: 410
I have following code:
$scope.showTotal = function() {
$scope.pT = [];
var iT = 0;
for (var i = 0; i < $scope.od.length; i++) {
console.log($scope.od[i]['bpr']);
iT += $scope.od[i]['bpr'];
// also tried this -> iT = iT + $scope.od[i]['bpr']
}
$scope.pT.push({iTotal: iT});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
But I don't know why it's not working.
If the bpr is for example 50 and 43.1034, then it logs the output in console something like this, iTotal:"050.000043.1034"
I am new to JavaScript and I started it directly with AngularJS. So please help me with arithmetic operators in JS. Thank You.
Upvotes: 0
Views: 61
Reputation: 1072
$scope.showTotal = function() {
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i < $scope.order.length; i++) {
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
// parseFloat will convert string to number and add the number instead of concatenating the strings
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
Upvotes: 2
Reputation: 6620
You are incrementing i inside the loop .Remove the duplicate i and I suspect that your $scope.order[i]['baseprice']
is not an integer. So convert it to an integer using parseFloat
$scope.showTotal = function(){
$scope.popupTotals = [];
var itemtotal = 0;
for (var i = 0; i<$scope.order.length; i++){
console.log($scope.order[i]['baseprice']);
itemtotal += parseFloat($scope.order[i]['baseprice']);
//also tried this -> itemtotal = itemtotal + $scope.order[i]['baseprice']
//i++; No need to increment here
}
$scope.popupTotals.push({itembasetotal : itemtotal});
console.log($scope.popupTotals);
$scope.showPopupNow = true;
}
Upvotes: 1