不除以零计算百分比变化

3

我有以下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个回答

8

从0到10的增长不能称之为百分比增长。您需要将该情况单独处理。

答案不是0%或100%。

可以选择以下方式之一:

  1. 告知函数的用户,该函数仅在旧值!= 0时有效

  2. 使用异常

  3. 返回NULL(由Jack Maney建议)


但我遇到的问题是$nLastMonthPeriod是自动生成的,而不是由用户控制,所以如果上个月没有数据,它就不应该返回任何东西,因为它不能除以零。 - SameOldNick
每次程序(我理解为“用户”)调用此函数时,您需要确保在出现除以零的情况下希望程序实际执行什么操作。然后,您可以使用NULL或异常来确定它是否发生。例如,如果您显示一个显示返回值的图形,则可能希望将其变灰。如果打印一些文本或符号表示发生了什么。没有魔法数字可以做到这一点。例如,如果您为此情况分配0,则人们会认为最后一个值也是10。如果您放置100%,人们会认为它是5等。 - Johan Lundberg

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

由于无法除以零(原因很多,既有技术性的也有平凡的),当 $nLastMonthPeriod==0 时最好返回 NULL


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

0
你可以简单地放置一个检查:
$nDifference = $nLastMonthPeriod == 0 ? 100 : ( ( ( $nCurrentPeriod - $nLastMonthPeriod ) / $nLastMonthPeriod ) * 100 );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接