I'm trying to store js number variables using sessionstorage but when I retrieve the variables from storage they behave like string variables when I add them together. I think this might have something to do with how I'm storing the variable using sessionStorage.setItem but not sure
I've saved the code at
Any help much appreciated. Cheers. Mike
<html>
<script src=".12.0/jquery.min.js"></script>
OUTPUT TOTAL IS:
<div id="TotalOutput"></div>
<br>
<script>
$(document).ready(function () {
InputTotals()
OutputTotals()
});
</script>
</html>
<script>
var input1 = 222
var input2 = 111
var input3 = 777
var input4 = 777
function InputTotals() {
var totalA = input1 + input2;
var totalB = input3 + input4;
sessionStorage.setItem("TotalA", totalA);
sessionStorage.setItem("TotalB", totalB);
}
function OutputTotals() {
var output1 = sessionStorage.getItem("TotalA");
var output2 = sessionStorage.getItem("TotalB");
var totaloutput = output1 + output2;
$("#TotalOutput").html(totaloutput);
}
</script>
I'm trying to store js number variables using sessionstorage but when I retrieve the variables from storage they behave like string variables when I add them together. I think this might have something to do with how I'm storing the variable using sessionStorage.setItem but not sure
I've saved the code at http://codepen.io/MHUMPHRI/pen/bpXpPm
Any help much appreciated. Cheers. Mike
<html>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.12.0/jquery.min.js"></script>
OUTPUT TOTAL IS:
<div id="TotalOutput"></div>
<br>
<script>
$(document).ready(function () {
InputTotals()
OutputTotals()
});
</script>
</html>
<script>
var input1 = 222
var input2 = 111
var input3 = 777
var input4 = 777
function InputTotals() {
var totalA = input1 + input2;
var totalB = input3 + input4;
sessionStorage.setItem("TotalA", totalA);
sessionStorage.setItem("TotalB", totalB);
}
function OutputTotals() {
var output1 = sessionStorage.getItem("TotalA");
var output2 = sessionStorage.getItem("TotalB");
var totaloutput = output1 + output2;
$("#TotalOutput").html(totaloutput);
}
</script>
Share
Improve this question
asked May 22, 2016 at 15:24
MikeMcClatchieMikeMcClatchie
791 gold badge2 silver badges11 bronze badges
2
-
Boils down to webStorage does store data as strings so if you need returned as number will need to cast to number again after
getitem()
– charlietfl Commented May 22, 2016 at 15:30 - cheers. that explains where I was going wrong! – MikeMcClatchie Commented May 22, 2016 at 15:52
2 Answers
Reset to default 6Use parseInt
(with radix 10, to be patible with older browsers) to parse a string to get an integer. Use parseFloat
if you're dealing with decimals.
var output1 = parseInt(sessionStorage.getItem("TotalA"), 10);
Number(var)
should work to define as number. Worked for me.