Rounding to the Nearest 0.5, Including Up and Down, and Handling Decimals Ending in 0

A big thank you to @kAlmAcetA for their contribution. Now, let’s address the question at hand: How can we round down the current time to the nearest 5 minutes in PHP, while also subtracting 5 minutes? We have two possible solutions for this. The first solution involves utilizing a loop, while the second solution can be found in the following resource: “Find number which is greater than or equal to N in an array”.

Question:

Hey, I’m encountering a few issues. I receive ratings and calculate their average. However, now I’m interested in the following:

1,2222222222222 = 1
1,2666666666666 = 1,5
2,3635345435435 = 2.5
2,567435 345345 = 2.5
3.5709 = 3
29,3003453450 = 29

I desire to round all numbers to the nearest 0.5, except for whole numbers which should be displayed without decimals (e.g., 3 instead of 3.0 or 4 instead of 4.0).

at the moment i have this code:

function roundRating($rating) {
    return floor($rating * 2) / 2;
}

can someone help me?
greets


Solution:

I have a suggestion, please refer to the comments for a detailed explanation of each step.

= 0.25)?0.5:0;
$int = $float - $remainder;
$result = $int + $roundedRemainder;
// If remainder is zero, cast to int to remove remainder.
if (fmod($result, 1) == 0)
        $result = (int)$result;
echo "Int: " . $int . "
"; echo "Remainder: " . $remainder . "
"; echo "Rounded remainder: " . $roundedRemainder . "
"; echo "Result: " . $result . "
";

Outputs:

Int: 1
Remainder: 0.753242342
Rounded remainder: 0.5
Result: 1.5

Frequently Asked Questions

Posted in Php