-1

Heyy guys,

I am trying to create an calculator that can sum.

What I am trying to do is:

  1. Search for the plus, and get the place of the plus in a number
  2. Get the product1 and product2
  3. Sum them together to y.value

Now as you can see this gives not like 3 + 2 = 5. But it gives 3 + 2 = 32

So i see that my script doesn't see this as a number but as a string. So what do I have to do to make it working?

Thnx for all your help!

function start() {
  var snelheid = 10;
  var x = document.getElementById("input");
  var y = document.getElementById("output");
  x.value = "3+2"

  function process() {
    var place_plus = x.value.indexOf("+");
    var product1 = x.value.slice(0, place_plus);
    var product2 = x.value.slice(place_plus + 1, x.value.length);
    y.value = product1 + product2;
    document.getElementById("var").innerHTML = product1 + " + " + product2 + " = " + (product1 + product2);
  }

  var animateInterval = setInterval(process, snelheid);
}

window.addEventListener('load', function(event) {
  start();
});
<textarea id="input"></textarea>
<textarea id="output"></textarea>

<p id="var"></p>
Thomas Pereira
  • 239
  • 1
  • 4
  • 18

1 Answers1

2

You can use the unary operator (+) to convert the string to a number:

var product1 = +x.value.slice(0, place_plus);
var product2 = +x.value.slice(place_plus + 1, x.value.length);
MrCode
  • 63,975
  • 10
  • 90
  • 112