0

Hi! My problem is that when you prompt a number and add it to another prompt is uses the "+" operator to join the lines. I want it to add the numbers together. How can I do this?

alert(prompt('add a number') + prompt('add another number'));

Thanks in advance, TheCoder

1
  • 1
    The prompt() function always returns a string, so you have to explicitly make the return values be numbers. You can do that by writing +prompt("...") instead of just prompt("...") Commented Jul 26, 2019 at 15:50

2 Answers 2

2

You can convert a string to a number with the + operator, like so:

+"50" + +"40" = 90

The result will be NaN if the strings can't be converted to a number (ie, +"fifty" => NaN), so you'll want to account for that in your code.

alert(+prompt('add a number') + +prompt('add another number'));
Sign up to request clarification or add additional context in comments.

4 Comments

I would note that using the + operator like this is technically considered a "hack" (even though it's defined in the ECMAScript specification and therefore isn't subject to breaking like many hacks), and it can make your code less readable. I would instead suggest using parseInt or parseFloat
That's a nice shorthand
@stevendesu In my experience, the + operator is far more common than the other methods, so I would say that although it may be hacky, it's an accepted standard practice and is therefore probably more recognizable (although admittedly less readable).
thanks for the help. Check out the site I needed that for @ novaos.tk
1

You need to use parseInt or parseFloat

alert(parseInt(prompt('add a number')) + prompt(parseInt('add another number')));

4 Comments

parseFloat()?
It's parseFloat() not parseDouble(), also those functions are not always the best things to use because they allow trailing non-numeric text; "123hello" will not cause an error.
I would maybe extend this answer by adding a check that the parseInt actually succeeded -- otherwise you risk adding NaN, or as @Pointy mentioned, falsely detecting 123hello as a number. Something like var input_one = prompt(...); var input_two = prompt(...); if (!isNaN(parseInt(input_one)) && parseInt(input_one).toString() === input_one && !isNaN(parseInt(input_two)) && parseInt(input_two).toString() === input_two) { alert(parseInt(input_one) + parseInt(input_two)); };
@stevendesu In something more complex, I agree checking for NaN does make sense... maybe throw an exception. But for a simple case, I think if you ask the user for 2 numbers to sum together and they enter bad input, NaN to me is fine