I am simulating a calculator using Javascript.
Where a user can input 2 numbers in a given text box, and it will display sum, product, difference and division.
Here is my function-
function calculate(num1, num2) {
console.log("First Number = " + num1 + " Second Number = " + num2);
console.log("Sum = " + (num1 + num2));
console.log("Product =" + (num1 * num2));
console.log("Difference = " + (num1 - num2));
console.log("Division = " + (num1 / num2));
}
When user inputs 1st number 4 and second number 3 i get this result:
First Number = 4 Second Number = 3
Sum = 43 // sum should be 7 NOT 43
Product = 12
Difference = 1
Division = 1.3333333333333333
Any ideas what is wrong here?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With