Javascript - Cannot Add 2 Numbers Correctly
Solution 1:
Because + is also a String Concatinater in JavaScript. use parseInt(var1) + parseInt(var2) it will work. also have a look on ---> Javascript Operators
to understand the + operator. Thanks
Solution 2:
If you're taking in the numbers in a text box they're treated as strings, so the +
operator will do string concatenation. The *
operator doesn't mean anything in relation to strings, so the javascript engine will try to interpret the inputs as numbers.
You can use parseInt on the inputs to convert them to numbers, or use the html number
input type.
Solution 3:
try
console.log("Sum = " + (parseInt(num1) + parseInt(num2)));
or
console.log("Sum = " + (0 + num1 + num2));
also make sure you are calling the function like
calculate(4, 3);
and not
calculate('4', '3');
Solution 4:
At least one of your inputs to calculate() is string. + is defined for string so become 43. While */- are not defined for string and Javascript "cleverly" convert them to int.
Post a Comment for "Javascript - Cannot Add 2 Numbers Correctly"