user1679941
user1679941

Reputation:

How can I add a number to a variable to which I assigned a number in Javascript?

I have the following:

var offset;
offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level) || 0;
offset += 100;

When I use the debugger this offset now has 0100. I want it to add like a number not a string. How can I do this?

Please note I changed the question slightly because I realized I was getting the value from local storage. I assume this returns a string. But I am still not sure how to solve this.

Upvotes: 0

Views: 71

Answers (1)

I Hate Lazy
I Hate Lazy

Reputation: 48761

The code you gave won't do that. I assume your value in your actual code is a numeric string. If so, the + will behave as a string concatenation operator, so you must convert the value to a number before using +.

You can do that with parseFloat().

var offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level);

offset = parseFloat(offset) || 0;

Or in most cases, you can simply use the unary version of + to do the conversion.

offset = +offset || 0;

Upvotes: 2

Related Questions