NaN是php输出
我面临一个小问题,但不幸的是无法解决它NaN是php输出,php,Php,我面临一个小问题,但不幸的是无法解决它 $rank = 13; //Sometimes empty or Null $hits = 3; //Sometimes empty or Null $rating = $rank/$hits; if(is_nan($rating)){ $ratings = 0; } if(is_numeric($rating) ){ $ratings = number_format((float)$rating, 2, '.', ''); }else{
$rank = 13; //Sometimes empty or Null
$hits = 3; //Sometimes empty or Null
$rating = $rank/$hits;
if(is_nan($rating)){
$ratings = 0;
}
if(is_numeric($rating) ){
$ratings = number_format((float)$rating, 2, '.', '');
}else{
$ratings = 0;
}
$res['rating'] = $ratings;
如果$rank或$hits为空,我将获得NaN作为输出。我做错了什么?因为您必须检查$hits的数量,使其不被零除
<?php
$rank = 13; //Sometimes empty or Null
$hits = 3; //Sometimes empty or Null
function isOkRankandHits($hank, $hits){
if(isset($hank) && isset($hits)) //Check if hank or hits are not null
return is_numeric($hits) && is_numeric($hank) && $hits > 0; //OK, you can make the division.
//You don't specify if hank could have negative values
return false;
}
$ratings = 0; //for security and maintenance, always work with a default value
if(isOkRankandHits($rank, $hits)){ // ratings will be numeric
$ratings = $rank / $hits;
$ratings = number_format((float)$ratings, 2, '.', '');
}
$res['rating'] = $ratings;
?>
您不能通过检查异常“除零”来检查任何样本代码。我已经用$hank和$hits测试了数字、空值和字符串值。对我来说,这段代码正在运行。php不能被零除。你会有一个错误
<?php
$rank = NULL; //Sometimes empty or Null
$hits = NULL; //Sometimes empty or Null
if(empty($rank))$rank =0;
if(empty($hits)){
$ratings =0;
} else {
$rating = $rank/$hits;
$ratings = number_format((float)$rating, 2, '.', '');
}
echo $ratings;
?>