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.

<?php
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 -

4 Comments »

Comment #2 by
d3x

How about:

function roundnum($num, $nearest){
return (ceil($num) / $nearest) * $nearest;
}
Comment #3 by
Mark

Thanks for the reply,

# php ./test.php
123

this is the problem that I was having, unfortunately all built in functions call to the closest integer.

Comment #6 by
Alix Axel

Sorry the last comment got messed up by the php tags.

echo roundnum(200, 9); // outputs 198 but shouldn’t it round to the nearest 9 (in this case 199)?
Comment #7 by
Mark

sorry, this rounds to the nearest multiple of 9, not to the closest number.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Note: All spam will be eaten by Dr Daves Spam Karma 2, remember spammers, what goes around, comes around...

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>