Rounding To The Nearest Integer Specified

Discussion in 'PHP' started by pradeep, Nov 27, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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.

    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);
      }
      
    Example:
    PHP:
      print roundToNearest(25.60,10)."<br/>";
      print 
    roundToNearest(2560,50)."<br/>";
      print 
    roundToNearest(2575,50)."<br/>";
      
    Output:
    Code:
      30
      2550
      2600
      
     
  2. LenoxFinlay

    LenoxFinlay Banned

    Joined:
    Apr 15, 2009
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  3. qforever

    qforever New Member

    Joined:
    Jan 22, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    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.:):):)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice