11
var current = 12000;
var june = 14600;
var may = 11200;

I want percent change with respect to 'current' month parameter. The output should be in percent and it can add or subtract w.r.t. the current month. How to do this?

Anuj Garg
  • 584
  • 7
  • 22
Sagar Suryawanshi
  • 195
  • 1
  • 1
  • 11

4 Answers4

31

Note that if one of your values is 0 you will get either -100% or Infinity%. This solves that problem:

   function percIncrease(a, b) {
        let percent;
        if(b !== 0) {
            if(a !== 0) {
                percent = (b - a) / a * 100;
            } else {
                percent = b * 100;
            }
        } else {
            percent = - a * 100;            
        }       
        return Math.floor(percent);
    }
Daniel Usurelu
  • 311
  • 3
  • 2
3

Its simple maths:

var res=(current-june)/current*100.0;
Anuj Garg
  • 584
  • 7
  • 22
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    I think this is backwards. It gives the percentage change of the current value vs. June, rather than the other way around. –  Jun 21 '15 at 18:37
  • @torazaburo: Agree, if comparing to current, it should be res=(x-curr)/curr, so that when x > curr, then res > 0. – Phil H Jun 24 '15 at 08:48
  • Right, it's backwards. However, sometimes you need to do it this way. Especially when comparing financial datas, where last quarter is "current" value. – InfiniteStack Nov 16 '22 at 22:08
2
var percentchange = (june - current) / current * 100.0;

If your answer is a negative number then this is a percentage increase else decrease.

Anuj Garg
  • 584
  • 7
  • 22
1

It isn't an easy task to handle specials cases, increase or decrease, rounding, over 100%, etc.

function calcPc(n1,n2){
  return (((n2 - n1) / n1 * 100).toLocaleString('fullwide', {maximumFractionDigits:3}) + "%");
}
   
   
   console.log(
   
     " May: "   , calcPc(11200,12000) ,
     "\nJune:" ,  calcPc(14600,12000)
   
   )
NVRM
  • 11,480
  • 1
  • 88
  • 87