0

I am trying to add some values within an array, but instead of outputting the sum, it prints the 2 values next to each other.

My array is:

$scope.values = [
  {amount: 5},
  {amount: 5}
]

My function is:

$scope.total = function() {
    var total = 0;
    angular.forEach($scope.values, function(item) {
        total += item.amount;
    })
    return total;
}

When i call {{ amountRemaining() }} it displays "55", instead of 10.

When i push another object to the array with a value of 6, it displays "556".

Another note to add, is that when i call {{values}}, it is placing the 5 inside "", which i think is the culprit.

"amount":"05"

How would i ensure the number is an integer?

1 Answer 1

2

You should coerce it explicitly.

total += Number(item.amount);

or

total += parseInt(item.amount);

The latter will make the effort to extract any valid number from the parameter, the first one will check if it's a number and either parse it or be NaN.

Sign up to request clarification or add additional context in comments.

Comments

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.