计算百分比变化而不除以零

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?

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;

You could simply put in a check:

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

Since you can't divide by zero (for many reasons, both technical and mundane), it would probably be best to return NULL when $nLastMonthPeriod==0.

An increase from 0 to 10 can not be described as a percentage increase. You need to treat that case separately.

The answer is not 0 % or 100 %.

Either

  1. tell the users of the function that it's only valid when the old value is != 0

  2. use exceptions

  3. return NULL (suggested by Jack Maney)

function percent($small, $large){
    if($large !=0){
    $percentCalc = ((100*$small)/$large);
    $percent = number_format($percentCalc, 1);
        return $percent;
    } else {
    return '0';
}
}