Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 941
MikeMcClatchie Avatar asked Sep 14 '25 16:09

MikeMcClatchie


1 Answers

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);
like image 124
Ates Goral Avatar answered Sep 16 '25 06:09

Ates Goral