Skip to content
Advertisement

Calculation in jquery

Trying to get Break Even Point (BEP) and selling value using jquery.

function roundToTwo(num) {
  return +(Math.round(num + "e+2") + "e-2");
}

$("#cost").on("change keyup paste", function() {
  var cost = Number($('#cost').val());
  var text
  var total_cost = roundToTwo(((cost * 18) / 100) + cost);

  var profit = -0.5;
  var sell = cost + 0.01;
  while (profit <= 0) {

    sell = sell + 0.01;
    profit = roundToTwo(sell - total_cost);


    text += "<br />New Sell " + sell + " and profit " + profit;
  }
  var bep = roundToTwo(sell - total_cost);
  $('#bep_display').text(bep);
  document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">

</h1>
<p id="testing"></p>

Now by running the above code, I entered 1 in the input, so the result (BEP) should be 0, but it gives NaN

Advertisement

Answer

Because your answer returns with e so it shows NaN. Try:

var bep = parseFloat(sell - total_cost).toFixed(8);

This will give you the result 0.00000000.

If you need a result as 0. Add:

bep = roundToTwo(bep);

function roundToTwo(num) {
  return +(Math.round(num + "e+2") + "e-2");
}

$("#cost").on("change keyup paste", function() {
  var cost = Number($('#cost').val());
  var text
  var total_cost = roundToTwo(((cost * 18) / 100) + cost);

  var profit = -0.5;
  var sell = cost + 0.01;
  while (profit <= 0) {

    sell = sell + 0.01;
    profit = roundToTwo(sell - total_cost);


    text += "<br />New Sell " + sell + " and profit " + profit;
  }
  var bep = parseFloat(sell - total_cost).toFixed(8);
  bep = roundToTwo(bep);
  $('#bep_display').text(bep);
  document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">

</h1>
<p id="testing"></p>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement