+ 1

Can any one tell me how to add numbers from user input

Eg function myFunction(a, b) { x= a+b; } myFunction (prompt ("number 1"),prompt ("number 2")); alert ("x") ; // out put is ab instead of a+b

9th Nov 2017, 2:18 PM
Jafari Ibrahim
Jafari Ibrahim - avatar
3 Respuestas
+ 15
x = Number(a) + Number(b) would solve it! There are many more ways though...
9th Nov 2017, 2:24 PM
Dev
Dev - avatar
+ 7
Basically, your problem is that you're trying to add strings together, rather than actual numbers. You'll just want to make sure you're using numbers, and convert the input to numbers as necessary. https://code.sololearn.com/W5IZ1VLHU1Aw/#html // This is using strings, so you're just concat'ing them together. function myFunction(a, b){ x=a+b; } myFunction("1", "2"); alert(x); OUTPUT: 12 // This is using numbers, so you can use addition function myFunction2(a, b){ x=a+b; } myFunction2(1, 2); alert(x); OUTPUT: 3 SOLUTION: // Number() - convert string to int function myFunction(a, b){ x=a+b; } myFunction(Number(prompt("number 1")), Number(prompt("number 2"))); alert(x); // parseInt() - convert string to int function myFunction(a, b){ x=a+b; } myFunction(parseInt(prompt("number 1")), parseInt(prompt("number 2"))); alert(x);
9th Nov 2017, 2:30 PM
AgentSmith
+ 3
Mr. Thanks you very much now I understand
9th Nov 2017, 2:35 PM
Jafari Ibrahim
Jafari Ibrahim - avatar