-3

I tried adding and subtracting negative numbers with this code

var num1 = parseInt(document.form1.num1.value);
var num2 = parseInt(document.form1.num2.value);
if(operand == "plus"){
    var sum = parseInt(num1+num2);
    // add alerts to check
    alert (num1);
    alert (num2);
    alert (sum);
}else{
    var sum = parseInt(num1-num2);
}

but when I print the result (sum), the program ignore the negative number and just count it as if it's a positive number. I tried delete the parseInt but nothing changes. for those who's confused : my inputs are num1 and num2. using the code I had, if I input (4) and (-2) and choose plus sign, sum = 6. they dont count the negative as negative, but as positive.

update : apparently even if I input (-2), they save it as (2).

Hikmah Az
  • 27
  • 1
  • 1
  • 6

1 Answers1

1

Assuming sum1 and sum2 are string literals, what you should do is parseInt(num1) + parseInt(num2)

It seems your problem is that you're applying a double negative, which makes a positive:

4 - -2 == 4 + 2
wvdz
  • 16,251
  • 4
  • 53
  • 90