Addition with variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Addition with variables

For some reason, when I try and use number variables instead of actual numbers for addition, it doesn't add them and instead just shoves them together. For example, if the variable num1=10 and the variable num2=2, if I tried doing num1+num2, it would output 102, which isn't what I want. Is there a way to actually add them instead? My full script is this: var num1=prompt("First number")} var math=prompt("Math type") var num2=prompt("Second number") if (math == "addition") {alert (num1+num2)}

3rd Oct 2018, 1:07 AM
Tyler
3 Answers
+ 1
The reason for this behaviour is that prompt() returns a string, regardless of what you input, so you actually perform string addition instead of math addition. To solve this, wrap your prompt() in a parseInt() call, e.g. var num1 = parseInt( prompt("...") ); For more information on parseInt(): https://www.w3schools.com/jsref/jsref_parseint.asp
3rd Oct 2018, 1:16 AM
Shadow
Shadow - avatar
+ 1
Use parseInt() or parseFloat() function to convert the user input (string value by default) to numeric values, based on your need whether to have the users enter float or integer numbers. For example, your script could be modified into the following to see the expected result: var num1 = prompt("First number"); var math = prompt("Math type"); var num2 = prompt("Second number"); if (math == "addition") {alert (parseFloat(num1) + parseFloat(num2))};
3rd Oct 2018, 1:32 AM
Alex
0
cxc
4th Oct 2018, 7:55 AM
Mykolas Sanda
Mykolas Sanda - avatar