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


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 :

enter image description here

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));

enter image description here


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


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

Tags:

Php