从百分比计算损失和利润

时间:2017-07-24 09:22:22

标签: javascript percentage

FIDDLE https://jsfiddle.net/o1hq1apw/2/

目前的BTC价格为2700美元 7天价格上涨了+ 34% 我持有3.011 BTC,我如何计算我的利润?

currentPrice = 2700;
percent = 34;
holdings = 3.011;
alert(  calcPec(currentPrice,percent,holdings)  );

目前的BTC价格为2700美元 价格在2天内上涨了-7% 我持有3.011 BTC,我该如何计算我的亏损?

currentPrice = 2700;
percent = -7;
holdings = 3.011;
alert(  calcPec(currentPrice,percent,holdings)  );


// This is what i have but it is not correct
function calcPec(currentPrice,percent,holdings)
{
   res = currentPrice*percent/2;
   sum = holdings*res;
   return '$'+sum;
}

3 个答案:

答案 0 :(得分:3)

所以你持有3.011 BTC,目前每个BTC为2700美元。 7天前,BTC的价格相当于100%,现在上涨了34%,因此2700美元等于134%。 要计算7天前的价格,您必须将2700除以134%,即约。 2014 $。 所以您的收入是(2700 - 2014)* 3.011 = 2065

您的代码应如下:

function calcPec(currentPrice, percent, holdings)
{
    oldPrice = currentPrice / ((100 + percent) / 100);
    sum = (currentPrice - oldPrice) * holdings;
}

答案 1 :(得分:1)

您忘记将百分比除以100得到分数。



// The current BTC price is 2700$.
// The price has increased by +34% in 7Days.
// I hold 3.011 BTC, how can i calculate my profit?

currentPrice = 2700;
percent = 34;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));


// The current BTC price is 2700$.
// The price has increased by -7% in 2Days.
// I hold 3.011 BTC, how can i calculate my loss?

currentPrice = 2700;
percent = -7;
holdings = 3.011;
console.log(calcPec(currentPrice, percent, holdings));

function calcPec(currentPrice, percent, holdings) {
  const curr = holdings * currentPrice;
  const changed = curr * (1 + (percent / 100));
  return '$' + (changed - curr);
}

 




将来您可能希望将百分比定义为开头的分数,以避免这样的错误。因此,不是percent = 34而是percent = 0.34

编辑也修复了其他错误;

答案 2 :(得分:0)

您可以将百分比值除以100到更改的分数。

function calcPec(price, percent, holdings) {
    return '$' + (holdings * price * percent / 100).toFixed(2);
}

console.log(calcPec(2700, 34, 3.011));
console.log(calcPec(2700, -7, 3.011));