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 で$nCurrentPeriod10 の場合、0 ではなく 100 を返す必要があるかどうかです。

4

5 に答える 5

8

0 から 10 への増加は、パーセンテージの増加として説明することはできません。その場合は別に扱う必要があります。

答えは0%でも100%でもありません。

また

  1. 関数のユーザーに、古い値が != 0 の場合にのみ有効であることを伝えます。

  2. 例外を使用する

  3. NULL を返す (Jack Maney の提案)

于 2012-01-22T08:50:16.133 に答える
2

$nLastMonthPeriod が 0で $nCurrentPeriod が 10 の場合、 0ではなく 100 を返す必要がありますか?

それはあなたがコーディングしたものです...

  if ( $nLastMonthPeriod == 0 )
        return 0;

もしかして?

  if ( $nLastMonthPeriod == 0 )
       if ($nCurrentPeriod>0)
          return 100; //whatever you want
       else
          return 0;
于 2012-01-22T08:48:08.517 に答える
2

ゼロで割ることはできないため (技術的な理由と日常的な理由の両方で)、NULLwhenを返すのがおそらく最善でしょう$nLastMonthPeriod==0

于 2012-01-22T08:48:40.920 に答える
0

あなたは単にチェックを入れることができます:

$nDifference = $nLastMonthPeriod == 0 ? 100 : ( ( ( $nCurrentPeriod - $nLastMonthPeriod ) / $nLastMonthPeriod ) * 100 );
于 2012-01-22T08:48:27.833 に答える
0
function percent($small, $large){
    if($large !=0){
    $percentCalc = ((100*$small)/$large);
    $percent = number_format($percentCalc, 1);
        return $percent;
    } else {
    return '0';
}
}
于 2013-01-30T04:29:28.777 に答える