0

I'm having trouble having the correct result. Below is my code

function Funtpcal() {
  var consiz = document.getElementById("consiz").value;
  var cmsn = document.getElementById("cmsn").value;

  var x = document.getElementById("tp_vol").value;
  var y = document.getElementById("tp_op").value;
  var w = document.getElementById("tp_tp").value;

    var z = -(((cmsn-100000)*(y*consiz*x))+(100000*w))/((cmsn+100000)*consiz*x);
    document.getElementById("tp").innerHTML = z.toFixed(3);
}
<input type="number" id="consiz" value="1000">
<input type="number" id="cmsn" value="1">
<input type="number" id="tp_vol" value="11.35">
<input type="number" id="tp_op" value="110">
<input type="number" id="tp_tp" value="100">

<input type="button" onclick="Funtpcal()" value="Calculate">
<span id="tp"></span>

Correct result is 109.989 as if you were to do this

var z = -(((1-100000)*(110*1000*11.35))+(100000*100))/((1+100000)*1000*11.35);

So tell me what is going wrong

andrewJames
  • 19,570
  • 8
  • 19
  • 51
Sultan
  • 75
  • 5
  • 6
    All of your values are strings so you're getting at least once accidental concatenation instead of addition with `cmsn+100000`. Either convert them to numbers or use `valueAsNumber` instead of `value`. see: [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – pilchard May 24 '22 at 23:11
  • For this specific calculation simply changing `(cmsn+100000)` to `(+cmsn+100000)` will make it return as expected, but best to understand why (see above), and in general explicitly parse input values to numbers to avoid unexpected errors. – pilchard May 24 '22 at 23:19
  • Quick fix is to change all of these, `document.getElementById` to `+document.getElementById`, a shorthand way of coercing a string to a number – danh May 24 '22 at 23:40

0 Answers0