Prince Mahmud Hridoy Prince Mahmud Hridoy - 6 months ago 10
Javascript Question

java scripts mathematical equation showing wrong answer

I am a new learner of Java Script. I'm having a problem with my mathematical equation. Its showing wrong answer.
please help me to find the mistake.



<html>
<head>
<title>calculation of (p+r)*(n+r) </title>

<script>
function calculate()
{
var p = document.getElementById("p").value;
var n = document.getElementById("n").value;
var r = document.getElementById("r").value;


var calculationa= p+r;

var calculationb= n+r;


var cal_final=Number(calculationa)*Number(calculationb);

document.getElementById("result").innerHTML=cal_final;
}
</script>
</head>

<body>
<h1>calculation of (p+r)*(n+r)</h1>
p: <input id="p"><br/>
n: <input id="n"><br/>
r: <input id="r"><br/>



<button onclick="calculate()">calculate</button>
<p id="result"></p>
</body>
</html>





It is the equation I want to solve.
The math shows this result which is not correct.http://i.stack.imgur.com/Ir9hs.png

How can i fix this ?

Answer

The values are assigned to p, n and r as strings. So, p+r = 1+2 = 12.

Use parseInt() to parse the values as Integer and do calculations. Or use parseFloat()

function calculate() {
  var p = parseInt(document.getElementById("p").value);
  var n = parseInt(document.getElementById("n").value);
  var r = parseInt(document.getElementById("r").value);

  var calculationa= p+r;

  var calculationb= n+r;

  var cal_final=Number(calculationa)*Number(calculationb);

  document.getElementById("result").innerHTML=cal_final;
}
    <h1>calculation of (p+r)*(n+r)</h1>
    p: <input id="p"><br/>
    n: <input id="n"><br/>
    r: <input id="r"><br/>

   <button onclick="calculate()">calculate</button>
   <p id="result"></p>