Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
Sagar Suryawanshi Avatar asked Jun 21 '15 17:06

Sagar Suryawanshi


People also ask

Can you use percentages in JavaScript?

One of them is the percent sign: % . It has a special meaning in JavaScript: it's the remainder operator. It obtains the remainder between two numbers. This is different from languages like Java, where % is the modulo operator.


2 Answers

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);
    }
like image 61
Daniel Usurelu Avatar answered Oct 10 '22 14:10

Daniel Usurelu


Its simple maths:

var res=(current-june)/current*100.0;
like image 38
Rahul Tripathi Avatar answered Oct 10 '22 14:10

Rahul Tripathi