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.
8 odpowiedzi
+ 1
Use parseInt(string)
hope this helps
Here is an example
https://code.sololearn.com/WW0fFXBzPIpz/?ref=app
0
Try:
var res=+fnum + +snum;
instead of
var res=fnum + snum;
0
OK,
0
but can u please little explain logic for doing this...
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
0
thanx mart
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
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.