How to convert string from LocalStorage to int /float Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to convert string from LocalStorage to int /float without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have functions to save and load variables to LocalStorage. When I retrieve them, they behave like strings. How can I simply convert these strings to ints/floats, so that I can perform mathematical operations on them.

My save and load functions are below.

function saveVars() {
    localStorage.setItem('moneyAdd', moneyAdd);
    localStorage.setItem('money', money);
    localStorage.setItem('crystals', crystals);
    localStorage.setItem('wood', rsword);
    localStorage.setItem('metal', metal);
    localStorage.setItem('sword', sword);
    localStorage.setItem('rsword', rsword);
    localStorage.setItem('hasAnvil', hasAnvil);
}

function loadVars() {
    moneyAdd = localStorage.getItem('moneyAdd');
    money = localStorage.getItem('money');
    crystals = localStorage.getItem('crystals');
    wood = localStorage.getItem('wood');
    metal = localStorage.getItem('metal');
    sword = localStorage.getItem('sword');
    rsword = localStorage.getItem('rsword');
    hasAnvil = localStorage.getItem('hasAnvil');
}

Answer

You are dealing with strings, localStorage would always return a string, so ‘1’ + 1 would be 11. You would need to convert the string to number, boolean, etc.

Maybe have a change in loadVars() like:

function loadVars() {
    moneyAdd = +localStorage.getItem('moneyAdd');
    money = +localStorage.getItem('money');
    crystals = +localStorage.getItem('crystals');
    wood = +localStorage.getItem('wood');
    metal = +localStorage.getItem('metal');
    sword = +localStorage.getItem('sword');
    rsword = +localStorage.getItem('rsword');
    hasAnvil = localStorage.getItem('hasAnvil') === 'true'
}
We are here to answer your question about How to convert string from LocalStorage to int /float - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji