-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,542
  • 26
  • 77
  • 130

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,246
  • 18
  • 72
  • 109
Patrick
  • 6,678
  • 3
  • 20
  • 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,331
  • 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,246
  • 18
  • 72
  • 109
0

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

BadIdeaException
  • 2,075
  • 13
  • 32