Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Rounding To The Nearest Integer Specified (http://www.go4expert.com/articles/rounding-nearest-integer-specified-t7565/)

pradeep 27Nov2007 12:37

Rounding To The Nearest Integer Specified
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 24Jul2009 10:01

Re: Rounding To The Nearest Integer Specified
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 25Jan2010 20:17

Re: Rounding To The Nearest Integer Specified
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.:):):)

All times are GMT +5.5. The time now is 07:14.