How to round up a number to nearest 10?

I was actually searching for a function that could round to the nearest variable, and this page kept coming up in my searches. So when I finally ended up writing the function myself, I thought I would post it here for others to find.

The function will round to the nearest variable:

function roundToTheNearestAnything($value, $roundTo)
{
    $mod = $value%$roundTo;
    return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}

This code:

echo roundToTheNearestAnything(1234, 10).'<br>';
echo roundToTheNearestAnything(1234, 5).'<br>';
echo roundToTheNearestAnything(1234, 15).'<br>';
echo roundToTheNearestAnything(1234, 167).'<br>';

Will output:

1230
1235
1230
1169

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10;

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.


round($number, -1);

This will round $number to the nearest 10. You can also pass a third variable if necessary to change the rounding mode.

More info here: http://php.net/manual/en/function.round.php

Tags:

Php

Rounding