Calculator Using Javascript Code
I am trying to make a small calculator with Javascript, but the two numbers are not added or subtracted, it just gets concatenated, for example, if I want to add 2+2 it outputs ' 2
Solution 1:
In JavaScript (and in many other programming languages), when you add two strings together, you get the concatenation of their values. Currently your program is treating the form inputs as strings, but you can use the built-in function parseInt
to extract integers from Strings.
Try the following:
functiongetResult() {
var result1 = parseInt(document.getElementById("number1").value);
var result3 = parseInt(document.getElementById ("op1").value);
var result2 = parseInt(document.getElementById("number2").value);
calculate (result1,result3,result2);
}
Solution 2:
Solution 3:
That is because of string concatenation. Please change the code to var res1 = parseInt(num1) + parseInt(num2);
Solution 4:
You must cast your vars to ints before doing any math with them. By default they are read in as strings. result1 = parseInt(result1)
Post a Comment for "Calculator Using Javascript Code"