0

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Arun P Johny Apr 27 '15 at 07:23
  • http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Arun P Johny Apr 27 '15 at 07:23
  • 2
    You're working with strings. Use [`parseInt`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/parseInt) or [`parseFloat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) appropriately. Also read the questions Arun linked. – Yoshi Apr 27 '15 at 07:26

2 Answers2

4

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);
Salman A
  • 262,204
  • 82
  • 430
  • 521
1

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>
Mackan
  • 6,200
  • 2
  • 25
  • 45