How to calculate % change from X to Y in PHP

1 Answer

0 votes
function percentChange(float $x, float $y): float {
    return (($y - $x) / abs($x)) * 100.0;
}

function describeChange(float $x, float $y): string {
    $pct = percentChange($x, $y);

    if ($pct > 0) {
        return sprintf("From %.1f to %.1f is a %.2f%% increase (+%.2f%%)", $x, $y, $pct, $pct);
    } elseif ($pct < 0) {
        return sprintf("From %.1f to %.1f is a %.2f%% decrease (%.2f%%)", $x, $y, abs($pct), $pct);
    } else {
        return sprintf("From %.1f to %.1f is no change", $x, $y);
    }
}

echo describeChange(-80.0, 120.0) . "\n";
echo describeChange(120.0, 30.0) . "\n";



/*
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)

*/

 



answered 5 hours ago by avibootz
...