calculate % change in javascript
Asked Answered
V

4

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?

Van answered 21/6, 2015 at 17:51 Comment(0)
H
3

Its simple maths:

var res=(current-june)/current*100.0;
Heteromorphic answered 21/6, 2015 at 17:53 Comment(3)
I think this is backwards. It gives the percentage change of the current value vs. June, rather than the other way around.Pox
@torazaburo: Agree, if comparing to current, it should be res=(x-curr)/curr, so that when x > curr, then res > 0.Artimas
Right, it's backwards. However, sometimes you need to do it this way. Especially when comparing financial datas, where last quarter is "current" value.Whispering
C
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);
    }
Chieftain answered 9/1, 2019 at 17:35 Comment(4)
This should be the accepted answer as it deals with the edge case scenarios.Negligent
Why have you got Math.floor in there?Accrete
@Accrete it's to return the largest integer without any decimals.Citriculture
percIncrease(100, 0); // -10000Trucking
H
3

Its simple maths:

var res=(current-june)/current*100.0;
Heteromorphic answered 21/6, 2015 at 17:53 Comment(3)
I think this is backwards. It gives the percentage change of the current value vs. June, rather than the other way around.Pox
@torazaburo: Agree, if comparing to current, it should be res=(x-curr)/curr, so that when x > curr, then res > 0.Artimas
Right, it's backwards. However, sometimes you need to do it this way. Especially when comparing financial datas, where last quarter is "current" value.Whispering
S
2
var percentchange = (june - current) / current * 100.0;

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

Shaft answered 21/6, 2015 at 17:55 Comment(2)
I tried with this. jsbin.com/vibofaleha/edit?html,js,output. and works perfectly fine..Van
Same thing, but I'd prefer to write (june/current - 1) * 100.Pox
T
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)
   
   )
Thither answered 21/11, 2018 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.