0

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.

4
  • 1
    Works fine for me -- jsfiddle.net/gQLVW Commented Oct 7, 2012 at 13:40
  • David - Sorry. I updated the question. I think this is my problem. I get the value from localStorage. Commented Oct 7, 2012 at 13:43
  • Sorry David. Please see my change to the question. If I do: offset = "0"; then it gives "0100" :-( Commented Oct 7, 2012 at 13:45
  • Anything inside quotes is a string, and adding "0" and 100 would be the same as adding "B" and 100, which would give you "B100" etc. Commented Oct 7, 2012 at 13:46

1 Answer 1

2

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;
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.