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;
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With