Home » Php » Round DOWN to nearest half integer in PHP

Round DOWN to nearest half integer in PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need a PHP function that will take a float and round it down to the nearest half (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

How to&Answers:
$x = floor($x * 2) / 2;

Answer:

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

Answer:

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

Answer:

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

Answer:

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

Answer:

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

}