jQuery中的计算

时间:2019-04-10 11:27:09

标签: javascript jquery

尝试获取盈亏平衡点(BEP),并使用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>

现在,通过运行上面的代码,我在输入中输入了 1 ,因此结果(BEP)应该为 0 ,但是它给出了 {{1 }}

2 个答案:

答案 0 :(得分:3)

因为您的答案以e返回,所以显示为NaN。试试:

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

这将为您提供结果 0.00000000

如果您需要结果为 0 。添加:

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>

答案 1 :(得分:2)

问题出在这一行:

var bep = roundToTwo(sell - total_cost);

一种解决方案是固定小数,例如:

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