Round up to nearest multiple of five in PHP

This can be accomplished in a number of ways, depending on your preferred rounding convention:

1. Round to the next multiple of 5, exclude the current number

Behaviour: 50 outputs 55, 52 outputs 55

function roundUpToAny($n,$x=5) {
    return round(($n+$x/2)/$x)*$x;
}

2. Round to the nearest multiple of 5, include the current number

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50

function roundUpToAny($n,$x=5) {
    return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}

3. Round up to an integer, then to the nearest multiple of 5

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55

function roundUpToAny($n,$x=5) {
    return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
}

Leave a Comment