Prince Mahmud Hridoy - 5 months ago 7x
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.

``````    <html>
<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>

<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 ?

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>``````