1

I am a beginner javascript programmer and I was just hacking away in notepad++ to get more familiar with methods/properties. I managed to get the user to be able to type in the operation and two numbers to be multiplied, divided, added, or subtracted. Everything works good with everything but when I try to add the two user inputted values, it doesn't output the two values added together, but it outputs two string concatenated together. Here's a code snippet of the add method:

if(this.operation == "add"){
this.num1 = prompt("enter first num");
this.num2 = prompt("enter second num");
alert( this.num1 + this.num2 );
};

The program opens up by asking "which operation would you like to use?";

| add "enter first num" |10 "enter second num" |12 answer:"1012"

it concatenates the string version of the two properties together when in reality I am just looking to use the plus sign as a math operator.

I look for the answer "22" instead of "1012" because I just want to add two numbers together after all.

I'm sure the answer is super simple, but this is my first question and I want to interact with the community a little more. Sorry if this is a dumb question and thanks for the help in advance!

Thrashmaniac89
  • 103
  • 1
  • 10
  • Welcome to [so]. It appears your question is the same as [How to force JS to do math instead of putting two strings together](http://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together): please let me know it that isn't the case. If you haven't already, I'd recommend taking the [tour] to learn more about Stack Overflow. Good luck! – Qantas 94 Heavy Aug 16 '14 at 07:54

2 Answers2

2

That is because prompt returns a string, you have to convert that in number.

alert((+this.num1) + (+this.num2));

Here + sign before this.num1 & this.num2 converts them to number.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

Try this old school solution.

alert( parseInt(this.num1,10) + parseInt(this.num2,10));

You need to convert string to int.

Here 10 inside parseInt() is to get the decimal form

doniyor
  • 36,596
  • 57
  • 175
  • 260