-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
0

4 Answers 4

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.

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

1 Comment

Don't forget to add the radix when you use parseInt.
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.

Comments

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().

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.