PHP: Rounding Numbers to the Nearest 5,10,12 or X

Here is a little helper function in PHP to round an integer number to the nearest X, where X can be any other integer number.  You can specify to force to round up, round down or whichever is closest (round up if it is the same in either direction).

function roundToNearest($input=null,$roundTo=5,$direction=”either”){
//$direction = up, down or either (default)
$output = “”;
switch ($direction) {
case ‘up’:
$output = $roundTo * ceil($input/$roundTo);
case ‘down’:
$output = $roundTo * floor($input/$roundTo);
$output = $roundTo * round($input/$roundTo);

$output = false;
return $output;

example usage:

echo roundToNearest(106,5,”up”);

result:   110

echo roundToNearest(106,12,”up”);

result: 108

echo roundToNearest(106,12,”down”);

result: 96

echo roundToNearest(110,12);

result: 108

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Apply your human brain cells and complete this highly complicated maths problem *