php – How to round number?

Question:

I need to use the following logic to round:

Numbers between x.1 and x.9 will be rounded to x.5, that is, it would look like this using examples:

1.0 = 1;
1.2 = 1.5;
1.9 = 1.5;

Any ideas on how to do this? I tried to find a ready-made PHP function but I couldn't find it.

Answer:

Can use fmod() function

function arred ($n) {
    $r = fmod($n, 1.0);
    if ($r != 0) {
        return $n - $r + 0.5;
    } else {
        return $n;
    }
}

Script with tests: http://codepad.org/slXVpUti .

Scroll to Top