Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating The Percentage Change Between Two Numbers

Tags:

php

math

Looking for some clarification on below code for calculating the percentage change between two different number of which the original could be a greater or smaller number. So will this code work for showing either a increase + or a decrease - change? Thanks.

$original= 100;
$current = 95;

$percentChange = (1 - $original / $current ) * 100;
like image 500
Anton S Avatar asked Oct 31 '25 02:10

Anton S


1 Answers

This function is more useful because it is protects from division by zero, the output is roundable, and it handles both positive (increase) and negative (decrease) return values.

if (! function_exists('pct_change')) {
    /**
     * Generate percentage change between two numbers.
     *
     * @param int|float $old
     * @param int|float $new
     * @param int $precision
     * @return float
     */
    function pct_change($old, $new, int $precision = 2): float
    {
        if ($old == 0) {
            $old++;
            $new++;
        }

        $change = (($new - $old) / $old) * 100;

        return round($change, $precision);
    }
}
like image 179
Luka Avatar answered Nov 02 '25 21:11

Luka