Reputation:
This is my JavaScript:
function straava() {
var input = document.getElementById('input').value
var r1 = document.getElementById('r1').value
var r2 = document.getElementById('r2').value
document.getElementById("output").innerHTML = r2 / (r1 + r2) * input;
}
Given values:
input = 5
r1 = 1000
r2 = 1000
The expected output is 2.5
, but this function produces 0.0004999500049995
. Why is that?
Upvotes: 0
Views: 118
Reputation: 272106
Your variables are strings. So here is what happens:
"1000" / ("1000" + "1000") * "5";
"1000" / "10001000" * "5";
// 0.0004999500049995
The +
(addition) operator concatenates strings instead of adding them, hence the incorrect result.
Convert your "numbers" to Number; using parseInt
/ parseFloat
functions, the (unary) +
operator or Number
function:
var input = parseInt(document.getElementById('input').value, 10);
var r1 = parseInt(document.getElementById('r1').value, 10);
var r2 = parseInt(document.getElementById('r2').value, 10);
Upvotes: 4
Reputation: 6271
You're not parsing the values to numbers, so it does the calculations on the strings. This happens because getting element values, through the use of .value
, will return type string.
function straava() {
var input = parseInt(document.getElementById('input').value);
var r1 = parseInt(document.getElementById('r1').value);
var r2 = parseInt(document.getElementById('r2').value);
document.getElementById("output").innerHTML = r2 / (r1 + r2) * input;
}
Below is an example of the different outputs, using both strings and ints.
function straava(p1, p2, p3) {
var input = p1 //document.getElementById('input').value
var r1 = p2 //document.getElementById('r1').value
var r2 = p3 //document.getElementById('r2').value
return (r2 / (r1 + r2) * input);
}
document.getElementById('output1').innerHTML = straava('5','1000','1000');
document.getElementById('output2').innerHTML = straava(5,1000,1000);
Using strings as parameters: <span id="output1"></span><br/>
Using integers as parameters: <span id="output2"></span>
Upvotes: 1