我从MYSQL数据库中获取数据后,我有一个简单的除法计算
$calculation = round($number1/$number2,2);
有时$ number2作为0从数据库出来,我得到除零错误,有没有办法防止除零警告并默认显示零?
答案 0 :(得分:3)
$gpg = $games == 0 ? 0 : round($goals / $games, 2);
$mpg = $goals == 0 ? 0 : round($minutes / $goals);
答案 1 :(得分:1)
使用条件:
$gpg = round($goals/($games ? $games : 1),2); // forces divisor to be 1 if $games == 0
$mpg = round($minutes/($goals ? $goals : 1,2); // forces divisor to be 1 if $goals == 0
注意:这会产生0
个值。您可能希望使用if
/ else
逻辑来说明某个数据“不适用”,或者在您有0
除数时尝试计算这些统计数据。
格式化:
echo number_format($theNumber, 2);
示例:
echo number_format(1, 2); // outputs 1.00
答案 2 :(得分:1)
if($goals != 0){
$gpg = round($goals/$games,2);
$mpg = round($minutes/$goals,2);
}
答案 3 :(得分:0)
您需要一个例外,或在检测到除零之前,请查看:
<?php
/* Detect division by zero in PHP
*
* More info:
*
* - http://rosettacode.org/wiki/Detect_division_by_zero
* - http://www.php.net/trigger_error
* - http://php.net/error_get_last
*
*/
function tryDivision($x, $y) {
$defaultVal = -1;
@trigger_error('');
$result = @($x / $y);
if( $result === false) {
/* Debug ERROR:
* $e = error_get_last();
* echo $e['message']; -> Division by zero
* more information check: var_dump($e);
*/
return $defaultVal;
}
return round($result, 2);
}
$gpg = tryDivision($goals, $games);
$mpg = tryDivision($minutes, $goals);