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
    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("...")` – Pointy Jul 26 '19 at 15:50

2 Answers2

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'));
Ian
  • 5,704
  • 6
  • 40
  • 72
  • 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` – stevendesu Jul 26 '19 at 15:53
  • That's a nice shorthand – GrafiCode Jul 26 '19 at 15:53
  • @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). – Ian Jul 26 '19 at 15:54
  • thanks for the help. Check out the site I needed that for @ http://novaos.tk –  Jul 26 '19 at 16:04
1

You need to use parseInt or parseFloat

alert(parseInt(prompt('add a number')) + prompt(parseInt('add another number')));
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • `parseFloat()`? – GrafiCode Jul 26 '19 at 15:52
  • 1
    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. – Pointy Jul 26 '19 at 15:52
  • 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 Jul 26 '19 at 15:56
  • @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 – ControlAltDel Jul 26 '19 at 16:03