2

If I use this code it makes from an number an string but I can't figure out why.

I want that this program adds 8+9 and makes = 17 not 89.

I try to learn this for as a hobby but I tried this almost a year ago and when I got stuck I never tried to make it work till now.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo_totaal"></p>
<p id="uitkomst1">8</p>
<p id="uitkomst2">9</p>

<script>

var a = document.getElementById("uitkomst1").innerHTML;
var b = document.getElementById("uitkomst2").innerHTML;
var total = a + b;
document.getElementById("demo_totaal").innerHTML = total;

</script>

</body>
</html>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Giovanni
  • 31
  • 6
  • 2
    Change your strings to numbers `parseInt(a) + parseInt(b)` should work as you expect. Read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – Ariel Nov 13 '18 at 22:46

3 Answers3

3

In JavaScript, you can use parseInt(string) to do that. Like,

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo_totaal"></p>
<p id="uitkomst1">8</p>
<p id="uitkomst2">9</p>

<script>
var a = document.getElementById("uitkomst1").innerHTML;
var b = document.getElementById("uitkomst2").innerHTML;
var total = parseInt(a) + parseInt(b);
document.getElementById("demo_totaal").innerHTML = total;
</script>
</body>
</html>
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

document.getElementById("uitkomst1").innerHTML returns the string, so your result will be a string of two strings added together.

You need to convert the string to a number if you want to add two numbers. Javascript has different ways to do this.

In your case, it should use the Number class to convert. I think it is the best option because it can convert decimal numbers too.

var numberA = new Number(a); // "8.1"
var numberB = new Number(b); // "9.1"
var total = numberA  + numberA ; // 17.2
Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
Bin
  • 26
  • 3
0

There are different methods to do this using parseInt/parseFloat/new Number. See other answers for this.

I use this mostly, multiply the number or string with 1 and then do addition. So far I havent seen any issues. Performance I am not sure though

var total = a*1 + b*1;

var a = "1";
var b = "12.5";

var total = a*1 + b*1;

console.log(total)
kiranvj
  • 32,342
  • 7
  • 71
  • 76