Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - cannot add 2 numbers correctly

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?

like image 500
Cute_Ninja Avatar asked Apr 14 '26 05:04

Cute_Ninja


2 Answers

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

like image 124
Meer Avatar answered Apr 16 '26 23:04

Meer


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.

like image 24
celeritas Avatar answered Apr 16 '26 22:04

celeritas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!