1

I have a section on my website that allows you to earn digital points and spend them on games and stuff, but it is hard to use. I am redoing it to make use of localStorage, and make the whole system easier to use. I ran into a problem, though. I created a function to add points using javascript, and I created a button that will temporarily allow me to run it easily. When I click the button, it should add 10 points to the current total of 0 points, and end up with 10 points total, but instead it adds 0 and 10 as strings and comes up with 010 points. This is the function that is run by pressing the button:

function addPoints(number) {
    var pointsExist = localStorage.getItem("points");
    var newPointsTotal = pointsExist + arguments[0];
    localStorage.setItem("points", newPointsTotal);
    location.reload();
}

This is the function that checks the current number of points and displays it:

function check() {
    var points = localStorage.getItem("points");
    if (!points) {
        var points = +0;
        localStorage.setItem("points", points);
    }
    document.getElementById("points").innerHTML = "Hi, " + username + "! You have " + points + " points.";
}

In case you find it helpful, I have created a hidden directory on my website with the page in it, and you can click on this link to go there and try it out yourself if I did not explain it well.

  • Possible duplicate of [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – Ivar Feb 09 '19 at 21:21

3 Answers3

1

Your points are saved as strings in localStorage. You should make a number.

function addPoints(number) {
    var pointsExist = localStorage.getItem("points");
    var newPointsTotal = Number(pointsExist) + arguments[0];
    localStorage.setItem("points", newPointsTotal);
    location.reload();
}
Praud
  • 297
  • 3
  • 13
0

In localStorage all the values are stringified, so pointsExist is given out as string. You have to change it to number before adding

function addPoints(number) {
    var pointsExist = localStorage.getItem("points");
    var newPointsTotal = parseInt(pointsExist) + arguments[0];
    localStorage.setItem("points", newPointsTotal);
    location.reload();
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

You need to parse the JSON in localStorage to integers:

function addPoints(number) {
    var pointsExist = parseInt(localStorage.getItem("points"));
    var newPointsTotal = pointsExist + number;
    localStorage.setItem("points", newPointsTotal);
    location.reload();
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79