-2

I am trying to make a simple addition using the following code but for some reason the result is a simple string concatenation instead of arithmetic addition. Can someone please tell me what I am missing here and how to fix this problem? Thanks

$scope.budget = localStorageService.get('budget'); //this returns 5000
$scope.toBeAdded = localStorageService.get('newAddition'); //this return 500

$scope.NewBudget = $scope.budget + $scope.toBeAdded; //return 5000500 instead of 5500
MChan
  • 6,842
  • 27
  • 83
  • 132

4 Answers4

1

localStorage is stored as a string. If you need an integer, you need to parseInt with the returned value. For example:

$scope.budget = parseInt(localStorageService.get('budget'), 10); //this returns 5000
$scope.toBeAdded = parseInt(localStorageService.get('newAddition'), 10); //this return 500

$scope.NewBudget = $scope.budget + $scope.toBeAdded;

If you are expecting decimal numbers, of course you need to use parseFloat instead of parseInt.

rg88
  • 20,742
  • 18
  • 76
  • 110
Patrick
  • 6,828
  • 3
  • 23
  • 31
1

Presumably $scope.budget and $scope.toBeAdded are being returned as strings instead of integers; however I don't think you have shared enough code for us to diagnose why. Try converting:

$scope.NewBudget = Number($scope.budget) + Number($scope.toBeAdded)

It uses the Number function to convert the strings to numbers.

JeffryHouser
  • 39,401
  • 4
  • 38
  • 59
1

Do this:

$scope.budget = parseInt(localStorageService.get('budget'), 10);
$scope.toBeAdded = parseInt(localStorageService.get('newAddition'), 10); 

It will make sure those value are passed as integers. Don't forget the radix at the end of parseInt().

rg88
  • 20,742
  • 18
  • 76
  • 110
0

Your variables are probably strings. You can turn them into numbers using Number(x)

BadIdeaException
  • 2,125
  • 15
  • 32