1

I am new to AngularJS, and I have a slight problem. I have a list of cities that I would like to compute the average temperature, and for some reason, after editing the temperature values in the list of cities, the function to compute the average temperature is returning incorrect values. It returns the correct value after loading the page, but after editing the temperature values I get incorrect results.

Here is my code:

<html ng-app>
<head>
    <title>Weather Comparison</title>
</head>
<body ng-controller='WeatherController'>
<h1>Weather Comparison</h1>
<div ng-repeat='item in items'>
    <span>{{item.city}}</span>
    <input ng-model='item.temp'>
    <input ng-model='item.humidity'>
    <input ng-model='item.wind'>
    <input ng-model='item.cloudiness'>
</div>
<div>The average temperature is {{avgTemp}}</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
    function WeatherController($scope) {
    $scope.items = [
        {city: 'Phoenix,AZ', temp: 38, humidity: 10, wind: 3, cloudiness: 10},
        {city: 'Atlanta,GA', temp: 30, humidity: 80, wind: 7, cloudiness: 40},
        {city: 'Honolulu,HI', temp: 32, humidity: 75, wind: 8, cloudiness: 30}
    ];

    //returns incorrect average values after editing default temperature values
    $scope.$watch(function() {
        var sum = 0;
        for (var i = 0; i < $scope.items.length; i++) {
            sum += $scope.items[i].temp;
        }
        $scope.avgTemp = sum / $scope.items.length;
   });
}

</script>
</body>
</html>

Does anyone know what am I doing wrong here?

1
  • It would be helpful if you set up a plunkr Commented Apr 24, 2014 at 20:57

1 Answer 1

2

The temperature is a string and you need to convert it to an integer (DEMO):

sum += parseInt($scope.items[i].temp, 10);

Or if you want to use floats:

sum += parseFloat($scope.items[i].temp);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. Instead of parseInt, I used parseFloat, and it worked.
No problem. Only depends on how accurate you want it to be.
Keep in mind that there are two args to parseInt(value, radix) where the radix defaults to base-8 if not specified. In other words, when parsing an integer in JS that's a base-10 number, use parseInt(value, 10);
@DougSwain Thanks for the reminder, updated the answer. Although I think the default 8 is not absolutely correct. It depends on the input string.
@MarcelGwerder good point. It does look like it's dependent on the input. Although what it chooses to do appears to be implementation dependent. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.