Possible Duplicate:
How to add two strings as if they were numbers?
I wrote a simple JavaScript code and I want to use two input box and add numbers from the two value. Here's the code, and I see the result 1520 instead of 35.
How can I fix it?
n1 <input type = "number" id = "n1" value=15 />
n2 <input type = "number" id = "n2" value=20 />
<p>Sum?</p>
<button onclick="sum()">Try it</button>
<p id="demo2">Result?? </p>
<script type="text/javascript">
function sum()
{
var fn, ln;
fn = document.getElementById("n1").value;
ln = document.getElementById("n2").value;
result = (fn+ln);
document.getElementById("demo2").innerHTML = result;
}
</script>
Use parseInt()
, or parseFloat()
; the problem you were experiencing is that you were concatenating two strings, not adding two numbers. parseInt()
(assuming that it finds a real number) addresses that issue by converting the string to a number:
function sum()
{
var fn, ln, result;
fn = parseInt(document.getElementById("n1").value, 10);
ln = parseInt(document.getElementById("n2").value, 10);
result = (fn+ln);
document.getElementById("demo2").innerHTML = result;
}
The , 10
that appears after the value
is the radix, which ensures which number-base the returned number (if any) will be.
Also note that the result
variable should be declared within the function as well, to avoid polluting the global scope (and possibly creating problems with other variables elsewhere).
References:
parseFloat()
.
parseInt()
.
result = (parseFloat(fn)+parseFloat(ln));