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

Variable Addition?

So I'm not that good at coding and I made a simple calculator, everything else works other than addition, it wont mathematically add the numbers together (ex. 1+1 = 11 other than 2) Heres the code: function Calc(){ var Var1 = prompt("What is the first digit of your equation?"); var Symbol = prompt("What is the mathematic symbol you are using for the equation? (/ for divison *for multiplication + for addition - for subtraction)"); var Var2 = prompt("What is the second digit of the equation?"); if (Symbol == "/"){ alert(Var1 / Var2); } if (Symbol == "*"){ alert(Var1 * Var2); } if (Symbol == "+"){ alert(Var1 + Var2); } if (Symbol == "-"){ alert(Var1 - Var2); } } Calc(); If any of you know how to fix this please tell me. (The simplest help best)

11th Dec 2019, 11:11 PM
YeetusYeetus
YeetusYeetus - avatar
3 Answers
+ 1
When one of the operators is a string and you use +, JS thinks you want to concatenate the strings. The remedy is to explicitly convert the strings into numbers using the function parseFloat. Here's how it works: https://www.w3schools.com/jsref/jsref_parsefloat.asp
11th Dec 2019, 11:14 PM
HonFu
HonFu - avatar
+ 1
I would also suggest using meaningful variable names and following some conventions. use camel case and avoid naming vars like var1 etc Also another suggestion - ask user for operation first - then insert both numbers.
12th Dec 2019, 12:31 AM
HNNX 🐿
HNNX 🐿 - avatar
0
Prompt always return a string, so you have to use Number(prompt()); to get a number type.
12th Dec 2019, 2:37 AM
Sebastián A
Sebastián A - avatar