Allen Lantz - 1 year ago 68
HTML Question

# Doing an equation in javascript?

I have this code and it always outputs 9 no mater what number i put in the textbbox. The equation is 0.25x^(2)+9, the ^(2) means squared.

``````<html>
<script>
function calc() {
var number = parseInt(document.getElementById('input').value);
var one = parseInt(0.25*number);
var two = parseInt(one*one);
var three = parseInt(two+9) ;
var sum = parseInt(three);
document.getElementById('num').innerHTML = sum;
}
</script>
<body>
<p>\$10 fee and 2 Commands are free!</p>
<input id="input" type="number" name="quantity" min="1" max="1000"></input><div id="num"></div>
<button onclick="calc()">Calculate</button>
</body>
``````

help?

Fiddle

I think that when you are casting it to an int everytime you are rounding everything down to 0 and then when you add +9 you alwasy get 9 as the answer so do:

``````    function calc() {
var number = parseInt(document.getElementById('input').value);
var one = 0.25*number;
var two = one*one;
var three = two+9;
var sum = three;
document.getElementById('num').innerHTML = sum;
}
``````

In addtion you have a methmetical mistake

``````var one = 0.25*number;
var two = one*one;
``````

two will be like saying `two = o.25^2 * x^2` and not `two = 0.25 * x^2` like you want so change it to:

``````function calc() {
var number = parseInt(document.getElementById('input').value);
var one = number*number;
var two = 0.25*one;
var three = two+9;
var sum = three;
document.getElementById('num').innerHTML = sum;
}
``````

And there is an even easyer way:

``````        function calc() {
var number = parseInt(document.getElementById('input').value);
var sum = 0.25*(number*number) + 9;
document.getElementById('num').innerHTML = sum;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download