php round up / ceil merge mysql AVG()

时间:2011-12-30 16:24:45

标签: php mysql rounding ceil

或Show Average我有这个:

$item = mysql_query("SELECT AVG(top) AS total FROM " . "$config_ccms_prefix" . "news where id='$id'"); 
while ($cms = mysql_fetch_assoc($item)) {
            $avg = ceil(($cms[total]),0.5);
        }
//......

示例: 如果$ ccms [total] = 3.4到3.5或7.8到8或9.3到9.5但不是9.5到10或4.5到5,我需要向上舍入。实际上,我不确定它是否可行。

$ avg对我不起作用!!

2 个答案:

答案 0 :(得分:1)

您需要这样做:

$avg = ceil($cms['total']*2)/2; //result of 

结果将是:

1.5 = ceil(1.1*2)/2; //CEIL(2.2) = 3.0 / 2 = 1.5;
1.5 = ceil(1.2*2)/2; //CEIL(2.4) = 3.0 / 2 = 1.5;
1.5 = ceil(1.3*2)/2; //CEIL(2.6) = 3.0 / 2 = 1.5;
1.5 = ceil(1.4*2)/2; //CEIL(2.8) = 3.0 / 2 = 1.5;
1.5 = ceil(1.5*2)/2; //CEIL(3.0) = 3.0 / 2 = 1.5;
2 = ceil(1.6*2)/2; //CEIL(3.2) = 4.0 / 2 = 2;
2 = ceil(1.7*2)/2; //CEIL(3.4) = 4.0 / 2 = 2;
2 = ceil(1.8*2)/2; //CEIL(3.6) = 4.0 / 2 = 2;
2 = ceil(1.9*2)/2; //CEIL(3.8) = 4.0 / 2 = 2;
2 = ceil(2*2)/2; //CEIL(4) = 4.0 / 2 = 2;

干杯

答案 1 :(得分:0)

此功能也很有帮助

// duplicates Excel's ceiling function
if (!function_exists('ceiling')) {
    function ceiling($number, $significance = 1) {
        return (is_numeric($number) && 
            is_numeric($significance) ) ? 
            (ceil($number / $significance) * $significance) : false;
    }
}
$data = array(1.2, 1.1, 3.5, 3.8, 4, 0.6, 4.1);
foreach ($data as $value) {
    echo $value . ' | ' . ceiling($value, 0.5) . '<br/>';
}

这将导致

1.2 | 1.5
1.1 | 1.5
3.5 | 3.5
3.8 | 4
4   | 4
0.6 | 1
4.1 | 4.5