Use PHP to round up to a nearest multiple

Published: 12 years ago

With this handy little function you can easily round up a given number to the nearest multiple of your choice.

The function

/**
 * Round up to the nearest multiple of your choice.
 *
 * @param int $number 
 * @param int $near
 * @return int
 */
function get_nearest_multiple( $number, $near ) 
{ 
     $nearest = round($number/$near)*$near;
      
     return $nearest;
}

An example

echo get_nearest_multiple(4.7,0.5); // prints 4.5
 
echo get_nearest_multiple(4.2,0.5); // prints 4

echo get_nearest_multiple(3.9,0.5); // prints 4

comments powered by Disqus
:?>