在while循环中计算JQuery [英] Calculation of JQuery in while loop

查看:63
本文介绍了在while循环中计算JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to calculate Break Even Point (BEP) using jquery:

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 running the above codes the result of BEP is 0.04. But it should be 0.

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

I think it's a technical problem (maybe in while loop) as the formula is correct. (Can be cross-checked in <h1>

推荐答案

进行交叉检查 buy = roundToTwo(买 - 0.01); 之前 while循环到期时给出.04结果。你需要减少购买循环的开始,而不是结束。在进入while之前设置 buy = sell ,然后移动 buy = roundToTwo (买 - 0.01); 到循环的开头。

It's that extra buy = roundToTwo(buy - 0.01); before the while loop expires that's giving the .04 result. You need to decrement buy at the beginning of the loop, not the end. Set buy = sell before it enters the while, then move buy = roundToTwo(buy - 0.01); to the beginning of the loop.

这会因为而给.03 var bep = roundToTwo(卖 - 买); ,这与输出 New Buy 9.97和利润0.01 一致。

That would give .03 as the result of var bep = roundToTwo(sell - buy);, which is consistent with the output New Buy 9.97 and profit 0.01.

这篇关于在while循环中计算JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆