MikeMcClatchie
MikeMcClatchie

Reputation: 79

session storage number variable stored as string

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.com/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>

Upvotes: 3

Views: 10519

Answers (2)

timpng1
timpng1

Reputation: 148

Number(var) should work to define as number. Worked for me.

Upvotes: 0

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140132

Use parseInt (with radix 10, to be compatible 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);

Upvotes: 6

Related Questions