PHP Round number to Nearest X
I did a few google searches on rounding numbers using PHP, unfortunately the only thing I could find is the round() function that doesn’t allow you to round to the nearest specified number.
function roundnum ($num, $nearest)
{
$ret = 0;
$mod = $num % $nearest;
if ($mod >= 0)
$ret = ( $mod > ( $nearest / 2)) ? $num + ( $nearest - $mod) : $num - $mod;
else
$ret = ( $mod > (-$nearest / 2)) ? $num - $mod : $num + ( -$nearest - $mod);
return $ret;
}
echo roundnum (1234, 15); // round to the nearest 15
echo roundnum (1234, 5); // round to the nearest 5
?>
Enjoy.
Filed under: code -
d3x
How about:
return (ceil($num) / $nearest) * $nearest;
}