ub3*_*t4r 2 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 );
}
Run Code Online (Sandbox Code Playgroud)
我想知道的问题是if $nLastMonthPeriod是0并且$nCurrentPeriod是10那么它应该返回100而不是0吗?
从0增加到10不能说是百分比增加.您需要单独处理该案例.
答案不是0%或100%.
或
告诉用户该函数只有在旧值为!= 0时才有效
使用例外
返回NULL(Jack Maney建议)