1

I am having a problem using localStorage in a game I am trying to make. Also a not is the money variable is designed to increase by 1 every second. Here's some of my code:

var money = 0;
window.onload = function () {
    load();
    window.setInterval(save, 2500);
};
function save(){
    localStorage.setItem("money", money);
};
function load() {
    document.getElementById("moneyText").innerHTML = localStorage.getItem("money");
};

My problem is that the save function is overriding the money variable every 2500 milliseconds. So I changed the innerHtml of the moneyText element to the same localStorage object like so:

function load() {
    document.getElementById("moneyText").innerHTML = localStorage.getItem("money");
    money = localStorage.getItem("money");
};

Which does save the value. However, now when it increases it shows up like this:

01
011
0111
...

Where as before I added that line it showed up as this:

1
2
3
...
johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Geroy290
  • 468
  • 2
  • 9
  • 24

2 Answers2

4

The values in Local Storage are always a string.

You could use parseFloat before you assign money.

 money = parseFloat(localStorage.getItem("money"));
Community
  • 1
  • 1
johnnyRose
  • 7,310
  • 17
  • 40
  • 61
2

localStorage holds only strings. Use:

money = parseFloat(localStorage.getItem("money"));

localStorage.setItem("money", money.toString());
Gavriel
  • 18,880
  • 12
  • 68
  • 105