Sagar Suryawanshi
Sagar Suryawanshi

Reputation: 195

calculate % change in javascript

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?

Upvotes: 11

Views: 19222

Answers (4)

NVRM
NVRM

Reputation: 13092

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

Upvotes: 1

Daniel Usurelu
Daniel Usurelu

Reputation: 311

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

Upvotes: 31

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

Its simple maths:

var res=(current-june)/current*100.0;

Upvotes: 3

Anuj Garg
Anuj Garg

Reputation: 582

var percentchange = (june - current) / current * 100.0;

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

Upvotes: 2

Related Questions