crm*_*ham 0 php decimal rounding
基本上我正在编写一个允许用户发布体育赛事的网站。然后会员可以对每个活动进行评分。评级系统为 10 分制:0.5、1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5、5.0。
有四类:
组织、物有所值、设施、乐趣因素
我使用字段将值存储在 mysql 数据库中float。
我使用了以下虚拟数据来测试系统。
当显示基于上述的事件评级时,我希望每个类别都四舍五入到上述 5 星级评级系统。
到目前为止,我有以下代码,除了舍入之外,它似乎工作正常。
例如:目前2.1666666666667我想将三个组织评级的平均值四舍五入为2.0。如果平均值是,4.6666666666667我希望它四舍五入到4.5。
但我该怎么做呢?
到目前为止我的代码如下:
// Count how many ratings this event has
if($ratingCount = $event->getEventRatingCount($event_id)){
// Get ratings for this event
$eventRating = $event->getEventRatings($event_id);
$organisation = 0;
$valueForMoney = 0;
$facilities = 0;
$funFactor = 0;
$overall = 0;
foreach($eventRating AS $rating){
$organisation = ($organisation + $rating['organisation'] / $ratingCount);
$valueForMoney = ($ValueForMoney + $rating['value_for_money'] / $ratingCount);
$facilities = ($facilities + $rating['facilities'] / $ratingCount);
$funFactor = ($funFactor + $rating['fun_factor'] / $ratingCount);
}
echo '<br />';
echo $organisation . '<br />';
echo $valueForMoney . '<br />';
echo $facilities . '<br />';
echo $funFactor . '<br />';
echo $overall = ($organisation + $valueForMoney + $facilities + $funFactor) / $ratingCount);
}else{
// no ratings for this event
}
Run Code Online (Sandbox Code Playgroud)
通过虚拟数据,我目前得到这些值:
2.1666666666667
1.6666666666667
4.3333333333333
2.1666666666667
3
Run Code Online (Sandbox Code Playgroud)
您可以将评级乘以 2,将其映射到 1..10 范围。然后四舍五入,除以 2。
$overall = round(2*$overall)/2;
Run Code Online (Sandbox Code Playgroud)
这会将 4.666 映射到 4.5,将 2.1666 映射到 2。3.888 的评级将向上舍入为 4。如果您希望始终向下舍入,请使用floor代替round。