+ 2
How to add 2 numbers correctly?
I'm trying to write my first code on JS, a calculator. But I can't make that works. var x = prompt ("first number"); var y = prompt ("second number"); alert (x+y); Ex: I put 1 and 2 and the results go to 12 instead 3. Just for curiosity I'm dropping my entire code (but he is in pt-br :-P. https://code.sololearn.com/W8wz4XlQ6SMP/?ref=app
4 Answers
+ 2
I understand the problem but don't understand the solution đ
+ 2
I resolve the problem I just change the 6 line to:
var z = Number (x) + Number (y)
this change string and Boolean to number
0
Although I couldn't understand most of your code output messages(My spanish isn't even elementary level)
My solution would be this:
The user input that you get from the prompt command is in the string data type, you have to convert this string to an integer or float after the input, then check if the user truly entered a number or he/she made a mistake
E.g:
var x = prompt('Enter number 1');
try{x = Number(x)}
catch(e){alert('Enter a real integer or float!')}
This code turns your input into a number
You could create a separate function for handling this, hope it helps
Edit:I noticed at the last line that your code prints out the workings and answer of your calculations, use this code to get the proper value of the answer instead of a concatenated string:
document.write (x + " + " + y + " = " +(x+y))
0
YupđSorry I'm not that good when it comes to explaining