Anton S
Anton S

Reputation: 43

Calculating The Percentage Change Between Two Numbers

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;

Upvotes: 4

Views: 8425

Answers (3)

Luka
Luka

Reputation: 603

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

Upvotes: 8

Niklesh Raut
Niklesh Raut

Reputation: 34914

Find difference and then count percentage like this

<?php
    $original= 100;
    $current = 115;
    $diff = $current - $original;
    $more_less = $diff > 0 ? "More" : "Less";
    $diff = abs($diff);
    $percentChange = ($diff/$original)*100;
    echo "$percentChange% $more_less agaist $original";
?>

Difference will be same for 110 and 90 against 100

Live demo : https://eval.in/872926

Upvotes: 7

Kays Kadhi
Kays Kadhi

Reputation: 560

Yes, it will work for showing either a increase + or a decrease - change.

Upvotes: 0

Related Questions