No addition support in calculator in JavaScript.

nisargshah95

Your Ad here
Hi, I am a beginner in programming. I just made a calculator in JavaScript but could find a way to add the integers. Here's my code -

Code:
<html>
<head>
<title>JavaScript Calculator</title>
<script type="text/javascript">
function calculator(p,q)
{
var r=prompt("Enter '-' sign for subtraction, '*' for multiplication, '/' for division, '^' for modulus and '+' for addition")
var p=prompt("Enter a value for 1st number");
var q=prompt("Enter a value for 2nd number");
if (r=="+")
{
return (p+q);
}
else if (r=="-")
{
return p-q;
}
else if (r=="*")
{
return p*q;
}
else if (r=="/")
{
return p/q;
}
else if (r=="^")
{
return p^q
}
}
</script>
</head>
<body>
<center><b>
<script type="text/javascript">
document.write(calculator(56,56));
</script>
</b></center>
</body>
</html>

But when during its execution while adding, it adds 10+20 as 1020 and 1+1 as 11. Please help me how to solve this. All other operations are working fine.

Thanks in advance.
Nisarg Shah
 
Last edited by a moderator:

Liverpool_fan

Sami Hyypiä, LFC legend
just use parseInt function so that the + sign is used as addition operation instead of concatenation.
Instead of:

Code:
var r=prompt("Enter '-' sign for subtraction, '*' for multiplication, '/' for division, '^' for modulus and '+' for addition")

put

Code:
var r=parseInt(prompt("Enter '-' sign for subtraction, '*' for multiplication, '/' for division, '^' for modulus and '+' for addition"))
do it for each of the variables that take input
 
OP
nisargshah95

nisargshah95

Your Ad here
Thanks for your reply, but I successfully debugged my code by putting p=p*1 and q=q*1 at the beginning so that JavaScript recognizes it as an integer. It works fine now.
 

nims11

BIOS Terminator
using the parseInt is a better approach to the problem.
alternatively you may also declare an integer as

var i= new Number();
 
Top Bottom