0

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.

6
  • Why you duplicate i++ at end? Commented Aug 8, 2017 at 6:34
  • removed it. @AlexanderAnikeev Commented Aug 8, 2017 at 6:37
  • What type do you have in the object $scope.order[i]['baseprice'] ? If it string, you must to parseFloat. Commented Aug 8, 2017 at 6:38
  • Thanks @AlexanderAnikeev for your help. It's working. Commented Aug 8, 2017 at 6:40
  • You are welcome! You have many correct answers at bottom. Check one of its! Commented Aug 8, 2017 at 6:43

2 Answers 2

2
$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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@RahulJain - Welcome!
1

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;
    }

2 Comments

Still the same result.
Is your $scope.order[i]['baseprice'] a string?. Try updated answer using parseFloat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.