在while循环中计算JQuery

时间:2019-04-11 11:38:38

标签: javascript php jquery

尝试使用jquery计算收支平衡点(BEP):

function roundToTwo(num) {
  return +(Math.round(num * 100) / 100);
}
var text = ""
var quantity = 1;
var buy = 0;
var sell = 10;
var bep_pnl = -0.5;
if (buy == 0) {
  buy = roundToTwo(sell - 0.01);
  while (bep_pnl < 0.01) {
    total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
    var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
    if (brokerage_amnt_buy >= 25) {
      var brokerage_buy = 25;
    } else {
      var brokerage_buy = brokerage_amnt_buy;
    }
    var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
    if (brokerage_amnt_sell >= 25) {
      var brokerage_sell = 25;
    } else {
      var brokerage_sell = brokerage_amnt_sell;
    }
    var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
    var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
    var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST


    var total_charges = roundToTwo(brokerage + transaction_charges + gst);
    bep_pnl = roundToTwo(((sell - buy) * quantity) - total_charges);

    text += "<br />New Buy " + buy + " and profit " + bep_pnl;

    buy = roundToTwo(buy - 0.01);
  }
  var bep = roundToTwo(sell - buy);
  $('#demo').text(bep);
  document.getElementById("testing").innerHTML = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="demo"></p>
<h1 id="testing"></h1>

运行上述代码时, BEP 的结果为 0.04 。但这应该是 0


我认为这是一个技术问题(可能在 while循环中),因为公式正确。 (可以在<h1>

中进行交叉检查

1 个答案:

答案 0 :(得分:0)

在while循环到期之前,额外的buy = roundToTwo(buy - 0.01); 给出了.04结果。您需要在循环的开始而不是末尾减少购买。在进入buy = sell之前先设置buy = roundToTwo(buy - 0.01);,然后将var bep = roundToTwo(sell - buy);移动到循环的开始。

这将得出New Buy 9.97 and profit 0.01的结果为0.03,与输出{{1}}一致。