calculate % change in javascript

18.1k views Asked by At
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?

4

There are 4 answers

3
Rahul Tripathi On BEST ANSWER

Its simple maths:

var res=(current-june)/current*100.0;
2
Anuj Garg On
var percentchange = (june - current) / current * 100.0;

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

0
NVRM On

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)
   
   )

4
Daniel Usurelu On

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