【问题标题】:Calculating percentage changes without dividing by zero计算百分比变化而不除以零
【发布时间】:2012-01-22 08:45:28
【问题描述】:

我有以下用于计算百分比减少或增加的 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?

【问题讨论】:

    标签: php math divide-by-zero


    【解决方案1】:

    从 0 到 10 的增加不能用百分比增加来描述。您需要单独处理这种情况。

    答案不是 0 % 或 100 %。

    要么

    1. 告诉函数的用户它仅在旧值为 != 0 时才有效

    2. 使用异常

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

    【讨论】:

    • 但我遇到的问题是 $nLastMonthPeriod 是自动生成的,并且不是用户控制的,所以它是否应该不返回任何内容,因为上个月有任何数据并且不能除以零?
    • 好吧,每次程序(用我的话来说:'用户')调用这个函数时,你需要确定你希望程序在被零除的情况下实际做什么。然后您使用 NULL 或异常来确定它发生了。例如,如果您显示一个显示返回值的图表,您可能希望将其设为灰色。如果打印一些文本或符号来表明发生了什么。没有神奇的数字会做。如果你为这种情况分配例如 0,人们会认为最后一个值也是 10。如果你输入 100%,人们会认为它是 5,等等。
    【解决方案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;
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        您可以简单地输入支票:

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

        【讨论】:

          【解决方案5】:
          function percent($small, $large){
              if($large !=0){
              $percentCalc = ((100*$small)/$large);
              $percent = number_format($percentCalc, 1);
                  return $percent;
              } else {
              return '0';
          }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-11-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-09-07
            • 2019-01-26
            • 1970-01-01
            • 2021-12-20
            相关资源
            最近更新 更多