Search code examples
phpmatharithmetic-expressions

Generate percentage of change between two numbers -- relative to the lesser number


I have a function that returns the growth percentage comparing the current value with the previous value. The only thing the function does is compare the number of registered users this week with the registered users the previous week. Of both values, you must return the percentage of growth or decrease.

/**
 * Generate percentage change between two numbers.
 *
 * @param float|int $original
 * @param float|int $current
 * @param int $precision
 * @return string
 */
function parsePercent($original, $current, int $precision = 2): string
{
    $result = (($current - $original) / $original) * 100;

    return round($result, $precision);
}

When the evaluation is done between two numbers where the new value is greater than the original, the percentage is returned correctly.

echo parsePercent(10, 20); // 100%
echo parsePercent(10, 30); // 200%
echo parsePercent(13, 16); // 23.08%
echo parsePercent(11, 22); // 100%

The problem occurs when the current value is less than the original value.

parsePercent(20, 10); // -50

At this point, the function should return -100 but it returns -50. Does anyone have any ideas how to fix this problem? Thanks!


Solution

  • Make the divisor the lesser of the two inputs:

    Code: (Demo)

    function parsePercent($original, $current, int $precision = 2): string
    {
        return round(
            ($current - $original) / min($original, $current) * 100,
            $precision
        );
    }
    
    echo "\n" . parsePercent(10, 20);  // 100%
    echo "\n" . parsePercent(10, 30);  // 200%
    echo "\n" . parsePercent(13, 16);  // 23.08%
    echo "\n" . parsePercent(11, 22);  // 100%
    echo "\n" . parsePercent(20, 10);  // -100%