Learn how to calculate a positive and negative percentage change between 2 numbers in JavaScript.

Willing to solve a simple percentage change in JavaScript? The first you need to do, is to think mathematically. You need to retrieve the difference (decrease or increase) between the numbers that you are comparing. This difference needs to be divided between the first number (the one that doesn't change). The result from this operation needs to be mulitplied by 100. Making an abstraction of this process in a JavaScript function, we would have:

/**
 * Calculates in percent, the change between 2 numbers.
 * e.g from 1000 to 500 = 50%
 * 
 * @param oldNumber The initial value
 * @param newNumber The value that changed
 */
function getPercentageChange(oldNumber, newNumber){
    var decreaseValue = oldNumber - newNumber;

    return (decreaseValue / oldNumber) * 100;
}

Note that if you change the orders of the old and new number, the answer would be different, so be sure that the first argument is the first version of the value, that means the one that didn't change and as second argument the value that changed.

Examples

The following examples show different cases of a percentage change both positive (decrease) as negative (increase) according to the point of view:

Note

A negative value indicates a percentage increase.

// X = 500
// Y = 234
// % = 53.2
getPercentageChange(500, 234);

// X = 1000
// Y = 890
// % = 11
getPercentageChange(1000, 890);

// X = 5
// Y = 2
// % = 60
getPercentageChange(5, 2);

// X = 100
// Y = 120
// % = -20
// Note: negative as it incremented 20%
getPercentageChange(100, 120);


// X = 500
// Y = 500
// % = 0
// Note: no percent change
getPercentageChange(500, 500);

Where can this function be used

For example, if you are working with image compression algorithms, you may want to display a human readable value in percent that indicates how much was compressed from the intial image, where the oldNumber is the original filesize e.g 1MB and the newNumber is 500KB which would result in a decrease of 50%.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors