Rounding To The Nearest Integer Specified

pradeep's Avatar author of Rounding To The Nearest Integer Specified
This is an article on Rounding To The Nearest Integer Specified in PHP.
While working with currency calculations, we often require to round a number to the nearest 10 or the nearest 50, like 407 should be 410.
I've written a function which will do exactly that, it requires two parameters the number to the round, and the integer to be rounded to. The function is like MROUND found in MS Excel & OpenOffice Spreadsheet.

Code: PHP
function roundToNearest($number,$nearest=50)
      $number = round($number);
      if($nearest>$number || $nearest <= 0)
          return $number;
      $x = ($number%$nearest);
      return ($x<($nearest/2))?$number-$x:$number+($nearest-$x);
Code: PHP
print roundToNearest(25.60,10)."<br/>";
  print roundToNearest(2560,50)."<br/>";
  print roundToNearest(2575,50)."<br/>";
LenoxFinlay's Avatar
Rounding involves reducing the number of significant digits in a number. The result of rounding is a "shorter" number having fewer non-zero digits yet similar in magnitude. The result is less precise but easier to use.
For example: 73 rounded to the nearest ten is 70, because 73 is closer to 70 than to 80.
Researchers may analyze rounding as a form of quantization.
qforever's Avatar
Light Poster
Function requires 3rd parameter: precision. Just to describe which part of number would be rounded(befoer dot or after). Also it will be fine if 4th parameter will allow to round prices to 99 cents. Like for input 16 it will return 15.99.