小提琴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美元。
价格在两天内上涨了-7%。
我持有3.011英镑,如何计算我的损失?
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;
}发布于 2017-07-24 09:27:28
你忘了把百分比除以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
编辑也修正了其他错误;
发布于 2017-07-24 09:35:43
所以你持有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;
}发布于 2017-07-24 09:31:32
您可以将百分比值除以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));
https://stackoverflow.com/questions/45276782
复制相似问题