Search code examples
phpmathdivide-by-zero

Calculating percentage changes without dividing by zero


I have the following the PHP that I am using to calculate percentage decreases or increases:

function CalculatePercentageIncrease( $nLastMonthPeriod, $nCurrentPeriod ) {
    if ( !is_numeric( $nLastMonthPeriod ) || !is_numeric( $nCurrentPeriod ) )
        return 0;

    if ( $nLastMonthPeriod == 0 )
        return 0;

    $nLastMonthPeriod = intval( $nLastMonthPeriod );
    $nCurrentPeriod = intval( $nCurrentPeriod );

    $nDifference = ( ( ( $nCurrentPeriod - $nLastMonthPeriod ) / $nLastMonthPeriod ) * 100 );

    return round( $nDifference );
}

The problem that I am wondering about is if $nLastMonthPeriod is 0 and $nCurrentPeriod is 10 then should it be returning 100 and not 0?


Solution

  • if $nLastMonthPeriod is 0 and $nCurrentPeriod is 10 then should it be returning 100 and not 0?

    Thats what you coded ...

      if ( $nLastMonthPeriod == 0 )
            return 0;
    

    did you mean?

      if ( $nLastMonthPeriod == 0 )
           if ($nCurrentPeriod>0)
              return 100; //whatever you want
           else
              return 0;