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

时间:2012-01-22 08:45:28

标签: php math divide-by-zero

我有以下用于计算百分比减少或增加的PHP:

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 );
}

我想知道的问题是,如果$nLastMonthPeriod为0且$nCurrentPeriod为10,那么它应该返回100而不是0吗?

5 个答案:

答案 0 :(得分:8)

从0增加到10不能说是百分比增加。你需要单独处理这个案子。

答案不是0%或100%。

无论

  1. 告诉用户该功能仅在旧值为时才有效!= 0

  2. 使用例外

  3. 返回NULL(Jack Maney建议)

答案 1 :(得分:2)

  

如果$ nLastMonthPeriod为0 且$ nCurrentPeriod为10则应该是   返回 100而非 0

这就是你编码的内容......

  if ( $nLastMonthPeriod == 0 )
        return 0;
你的意思是?

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

答案 2 :(得分:2)

由于您不能除以零(出于多种原因,无论是技术还是世俗),最好在NULL时返回$nLastMonthPeriod==0

答案 3 :(得分:0)

你可以简单地检查一下:

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

答案 4 :(得分:0)

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