ronblackHP
1/24/2020 - 2:33 PM

JS addition Garbage

<!DOCTYPE html>
<html>
<body>

<p>This is something weird I ran into because JS always converts eveythig to a string.</p>
<p>So when adding you need to cast it back to a number.</p>
<p>Sometimes BUT NOT ALWAYS you get something funky back... here is the sometimes situation.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x1 = .1;
  var x2 = .2;
  var x3 = x1+x2;

  var n = 
  "x1 = " + x1 + "<br>" + 
  "x2 = " + x2 + "<br><br>" + 
  "var x3 = x1+x2;<br><br>" + 
  "x3 = " + x3 + "   WTF???<br>" + 
  "x1 + x2 = " + x1 + x2 + " WTF???<br>" +
  "(x1 + x2) = " + (x1 + x2) + " WTF???<br>" +
  "Number(x1) = " + Number(x1) + "<br>" + 
  "Number(x2) = " + Number(x2) + "<br>" + 
  
  "(Number(x1) + Number(x2)) = " + (Number(x1) + Number(x2)) + " WTF???<br>" +
  "(parseFloat(x1) + parseFloat(x2)) = " +(parseFloat(x1) + parseFloat(x2)) + " WTF???<br><br>" +
  "(Number(x1) + Number(x2))<b>.toFixed(2)</b> = " + (Number(x1) + Number(x2)).toFixed(2) + " Ahh now thats better.  I tacked on .toFixed(2)<br><br> <b>BUT WHY do we need to do that?</b>"
  ;
  document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>