I. Smith I. Smith - 8 months ago 39
Javascript Question

Local Storage is messing up my variable increments

When I set variables to localStorage, like so..

localStorage.setItem('gold', gold);

And then I recall them like this...

gold = localStorage.getItem('gold');

It messes up some of my functions that worked before, for instance

ore += orepm;
}, 60000);

Instead of making it 112 from 100 (+12 each minute), it makes it 10012. It's basically adding the number to the end of the starting number, like a string. I believe that it has to do with localhost changing format but I'm not sure and have no idea how to fix it.

Thanks for the Help!


parseInt() is your friend. Although it's unclear from your question how gold relates to ore (or indeed orepm), you should use parseInt() (or parseFloat() if needed) when retrieving the value:

gold = parseInt( localStorage.getItem('gold') );

It's worth noting some of the intracicies of parseInt() -- for example:

parseInt('1kjjdfud') == 1;

So you may wish to use Javascript's casting mechanism (i.e. Number('1')), if you correctly handle NaN:

gold = Number( localStorage.getItem('gold') );