0

I have an array like this.

$scope.addit=[{name:'A',amt:0},{name:'B',amt:0},{name:'C',amt:10},{name:'D',amt:100}];
$scope.TSUM = 100;

var total_Add = 0;

          var amnt =0;
        angular.forEach($scope.addit, function(item) {
            if(item.name == 'A'){
                amnt = $scope.TSUM;

            }
            else if(item.name == 'B'){
                amnt = $scope.TSUM + 10;
            }

            else if(item.name != 'A' && item.name != 'B' ){
                amnt = item.amount;

            }

            total_Add =  total_Add+amnt;

        })

My code should return the sum. But here it is concatenating all values. I get like 10011010100.

Please help me. It is making issue while adding item.amount.

athi
  • 123
  • 9

3 Answers3

0

+ is used for concatenation in javascript, so for addition You have to use eval()

So write your code as follow

 amnt = eval($scope.TSUM +"+ 10");

So it looks like

amnt = eval("20 + 10");
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37
  • 1
    Indeed, `+` is used for concatenation but only with strings. When we are working with numeric variables, `+` is used for addition. Also `eval` is evil https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – andale Jul 29 '16 at 10:28
  • your ans is right for item.amount.. When i use eval(item.amount) my issue fixed. But no need of eval on $scope.TSUM+10. – athi Jul 29 '16 at 10:35
0

You can use parserInt or parseFloat

amnt = parserInt($scope.TSUM) + 10;
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
-1

var total_Add = 0;

      var amnt =0;
    angular.forEach($scope.addit, function(item) {
        if(item.name == 'A'){
            amnt = $scope.TSUM;

        }
        else if(item.name == 'B'){
            amnt = $scope.TSUM + 10;
        }

        else if(item.name != 'A' && item.name != 'B' ){
            amnt = eval(item.amount);

        }

        total_Add =  total_Add+amnt;

    })
athi
  • 123
  • 9