FilipPaul
FilipPaul

Reputation: 13

Operators glitched? (JavaScript)

For some reason in my program, the + sign adds two digits together, in my code:

numerator1 += wholenumber1 * denominator1;

If wholenumber1 is 1 and denominator1 is 4, then the numerator1 is 14... I found this out by:

console.log(numerator1);

This is using inputs with type="number", and the other parts of the equation are working just fine... But this part is essential in order for my program to run properly, and help is greatly appreciated!

Upvotes: 0

Views: 38

Answers (2)

Mamun
Mamun

Reputation: 68923

Though the input type is number, the actual value is of type string. You can check this by typeof operator. So you have to use functions like parseInt() to convert the value to integer in order to perform actual arithmetic operation.

console.log(typeof(document.getElementById('num1').value));
<input type="number" id="num1" value="1"/>

Code Example:

var numerator1 = 0;
var wholenumber1, denominator1;
wholenumber1 = document.getElementById('wholenumber1').value;
denominator1 = document.getElementById('denominator1').value;

numerator1 += parseInt(wholenumber1) * parseInt(denominator1);

console.log(numerator1);
wholenumber1: <input type="number" value="1" id="wholenumber1" /> <br/>
denominator1: <input type="number" value="4" id="denominator1" />

Upvotes: 1

E_K
E_K

Reputation: 2249

You need to convert the input into integers for this to work. You can use use numerator1 += parseInt(wholenumber1) * parseInt(denominator1); Refer to This for more

Upvotes: 1

Related Questions