Adding problem, i want 2+2=4, but its giving 2+2=22; how to correct it. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Adding problem, i want 2+2=4, but its giving 2+2=22; how to correct it.

function add() { var fnum=document.getElementById("fnum").value; var snum=document.getElementById("snum").value; var res=fnum+snum; document.write(res); } this is my code to add to numbers, but its simply joining 2 numbers, like+ 2+2=22; I am not getting why its so.

15th Jun 2017, 6:03 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
8 Answers
+ 1
Use parseInt(string) hope this helps Here is an example https://code.sololearn.com/WW0fFXBzPIpz/?ref=app
15th Jun 2017, 7:17 PM
Limitless
Limitless - avatar
0
Try: var res=+fnum + +snum; instead of var res=fnum + snum;
15th Jun 2017, 6:15 PM
Maart
Maart - avatar
0
OK,
15th Jun 2017, 6:16 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
0
but can u please little explain logic for doing this...
15th Jun 2017, 6:17 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
0
Yeah, the + symbol evaluates the string as a number. You're adding up two strings now, so setting them both to a number value will make them add up. See http://xkr.us/articles/javascript/unary-add/ for a detailed explanation
15th Jun 2017, 6:21 PM
Maart
Maart - avatar
0
thanx mart
15th Jun 2017, 6:49 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
0
Number() class makes sure if the value is a Number or not So modify your script like this. function add() { var fnum=Number(document.getElementById("fnum").value); var snum=Number(document.getElementById("snum").value); var res=Number(fnum+snum); document.write(res); } I hope it works
15th Jun 2017, 7:05 PM
Din Esh
Din Esh - avatar
0
thanx to all of you, if possible I want to discuss more, on creating a calculator, my problem in creating calculator- 1. TO GET AS MANY VALUES AS POSSIBLE. 2.TO MAKE A FUNCTION WHICH CLEAR VALUE. 3. TO MANAGE VARIOUS OPERATORS GIVEN BY USER 4. TO SHOW DISPLAY LIMIT ERROR AND SYNTAX ERROR. I AM GOOGLING OUT ABOUT THIS, BUT LITTLE LITTLE HELP AND HINTS CAN FILL UP MY OCEAN.
15th Jun 2017, 7:49 PM
ASHISH PANDEY
ASHISH PANDEY - avatar