Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this code using angular js:

<!DOCTYPE html >
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script type="text/javascript">
        function TodoCtrl($scope) {
            $scope.total = function () {
                return $scope.x + $scope.y;
            };

        }
    </script>
</head>
<body>
   <div ng-app>
  <h2>Calculate</h2>

  <div ng-controller="TodoCtrl">
    <form>
        <li>Number 1: <input type="text" ng-model="x" /> </li>
        <li>Number 2: <input type="text" ng-model="y" /> </li>
        <li>Total <input type="text" value="{{total()}}"/></li>       
    </form>
  </div>
</div>

</body>
</html>

I am able to do multiplication, division and subtraction but for addition, the code just concatenates the x and y values (i.e. if x = 3 and y = 4, the total is 34 instead of being 7)

What am I doing wrong?

share|improve this question

2 Answers

up vote 2 down vote accepted

If that is indeed the case then what is happening is the values that are being passed in for x and y are being treated as strings and concatenated. What you should do is convert them to numbers using parseInt

return parseInt($scope.x) + parseInt($scope.y);

or if you prefer brevity

return $scope.x|0 + $scope.y|0;
share|improve this answer
Isn't that something! Where can I learn more about this kind of brevity? – mpora Mar 26 at 22:44
1  
@mpora - Just through poking around I guess. I am not aware of a site that has all of the shortcuts displayed in a list. I got that one from this post about guid's: stackoverflow.com/a/2117523/1026459 – Travis J Mar 26 at 22:45
Thanks, I am always looking for brevity. – mpora Mar 26 at 22:48

You want this:

   return parseFloat($scope.x) + parseFloat($scope.y);

+ overrides string concatenation when you have 2 strings. You'll need to cast them to integers or floats explicitly. -,*,/ will all cast to numbers if possible.

share|improve this answer
parseFloat works but not parseInt, interesting. – mpora Mar 26 at 22:42
are they integers? if not that would be why. What doesn't work about parseInt? – ben336 Mar 26 at 22:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.