PHP – Round a value up to the nearest multiple value

php-banner

print
round(), ceil() and the like to a good job of most things in PHP.

But what if you need to round the number up to the nearest 10 or nearest 15 etc.  This little function makes this easy:

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

Usage:

$number= roundToNearestMultiple($input, 10);

/* 
    Outputs:
      $input= 7 -> $number= 10
      $input= 85 -> $number= 90
*/

$number= roundToNearestMultiple($input, 15);

/* 
    Outputs:
      $input= 89 -> $number= 90
      $input= 1869 -> $number= 1875
*/

 

Share this post:
Related Posts
Getting the value or text of an HTML attribute using jQuery
php-banner
How to capitalise the first word of each sentence – PHP
2 Comments
  • CodersRme
    Sep 6,2018 at 4:39 pm

    Thanks for sharing this. Nice and easy to follow. Will this work in PHP7?

    • Fluffy
      Sep 7,2018 at 8:06 am

      Hey CodersRme. No problem, and yes it should work in 7 🙂

Leave a Comment