开发者

Round DOWN to nearest half integer in PHP

I need a PHP function that will take a float and round it down to the nearest half 开发者_如何学Python(x.0 or x.5). I found other functions that will round to the nearest fraction, but they round both ways.

The function I need can only round down.

Examples

7.778 -> 7.5

7.501 -> 7.5

7.49 -> 7.0

7.1 -> 7.0


$x = floor($x * 2) / 2;


I'm assuming PHP has a floor function: floor($num * 2) / 2 ought to do it.


A easy solution is to use modulo operator (fmod() function), like this :

function roundDown($number, $nearest){
    return $number - fmod($number, $nearest);
}

var_dump(roundDown(7.778, 0.5));
var_dump(roundDown(7.501, 0.5));
var_dump(roundDown(7.49, 0.5));
var_dump(roundDown(7.1, 0.5));

And the result :

Round DOWN to nearest half integer in PHP

The advantage it's that work with any nearest number (0.75, 22.5, 3.14 ...)

You can use the same operator to roundUp :

function roundUp($number, $nearest){
    return $number + ($nearest - fmod($number, $nearest));
}

var_dump(roundUp(7.778, 0.5));
var_dump(roundUp(7.501, 0.5));
var_dump(roundUp(7.49, 0.5));
var_dump(roundUp(7.1, 0.5));

Round DOWN to nearest half integer in PHP


You can do it on that way round($number / 5, 1) * 5 the second parameter in the round() is the precision.

Example with $number equal to 4.6, 4.8 and 4.75

>>> round(4.6 / 5, 1) * 5;
=> 4.5
>>> round(4.8 / 5, 1) * 5;
=> 5.0
>>> round(4.75 / 5, 1) * 5;
=> 5.0

If you want you can round() down too like round($number, 1, PHP_ROUND_HALF_DOWN) check the documentation for more information https://www.php.net/manual/en/function.round.php


echo round($val*2) / 2;    // Done


From my job's requirements. I put an function to do this. Hope you can view it as a reference:

function round_half_five($no) {

    $no = strval($no);
    $no = explode('.', $no);
    $decimal = floatval('0.'.substr($no[1],0,2)); // cut only 2 number
    if($decimal > 0) {
        if($decimal <= 0.5) {
            return floatval($no[0]) + 0.5;
        } elseif($decimal > 0.5 && $decimal <= 0.99) {
            return floatval($no[0]) + 1;
        }
    } else {
        return floatval($no);
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜