Calculate loss and profit from percentage

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

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;
alert(  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;
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;
}

Answer

You forgot to divide the percentage by 100 to get a fraction.

// 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);
}

 

In future you probably want to define your percentage as a fraction to begin with, to avoid errors like this. So instead of percent = 34 you’d do percent = 0.34

EDIT fixed other errors too;

Leave a Reply

Your email address will not be published. Required fields are marked *