Round up to nearest multiple of five in PHP

Round down:

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

Round up:

$x = ceil($x/5) * 5;

Round to closest (up or down):

$x = round($x/5) * 5;

   echo $value - ($value % 5);

I know it's an old question, but IMHO using modulus operator is the best way, and far more elegant than the accepted answer.


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

  1. Divide by 5
  2. round() (or ceil() if you want to round up always)
  3. Multiply by 5.

The value 5 (the resolution / granularity) can be anything — replaced it in both step 1 and 3

So in summary:

    $rounded_number = ceil( $initial_number / 5 ) * 5