+ 2
What's wrong in my code?
I made a very simple calculator using JavaScript, but the addition feature isn't working properly. For example, if I add 2+2 it shows 22 as result. Can anybody tell me the right way to do addition? I am a beginner in JavaScript. https://code.sololearn.com/W9FYG6CqR2bw/?ref=app https://code.sololearn.com/W9FYG6CqR2bw/?ref=app
6 Respuestas
+ 1
function add() {
var first = Number(prompt("Enter the first number"));
var second = Number(prompt("Enter the second number"));
var result = first + second;
document.write("The Answer is "+result);
}
Prompt take input as string type..
+ is also used for cancatination of string.. There cancatination taking place because of string type.
Convert to number..
For other operators, its taking implicit convertion..
+ 2
Jayakrishna🇮🇳 Thanks 🙏 Now it works ☺️
+ 2
Jayakrishna🇮🇳 Alexandr Dragunov I have updated it now and added dark theme UI ☺️
https://code.sololearn.com/WioNPJqa5z6h/?ref=app
+ 2
Mulla Aman Lalasahab Thanks bro for supporting, but my problem has already solved. Check the comments 😊😊
+ 1
Shahid Ali
Also alternatively,
instead of Number function, you can use + as specified above,
Ex:
var x=prompt(" ");
x= +x;
Now x is converted to number type...
Or
var x= +prompt("");
You're Wel come...
+ 1
var result = +first + +second;