public Method

Float.round

flt.round    integer

Rounds flt to the nearest integer. Equivalent to:

def round
  return (self+0.5).floor if self > 0.0
  return (self-0.5).ceil  if self < 0.0
  return 0
end

1.5.round      #=> 2
(-1.5).round   #=> -2

Source Code

/*
*  call-seq:
*     flt.round   => integer
*  
*  Rounds <i>flt</i> to the nearest integer. Equivalent to:
*     
*     def round
*       return (self+0.5).floor if self > 0.0
*       return (self-0.5).ceil  if self < 0.0
*       return 0
*     end
*     
*     1.5.round      #=> 2
*     (-1.5).round   #=> -2
*     
*/

static VALUE
flo_round(num)
   VALUE num;
{
   double f = RFLOAT(num)->value;
   long val;

   if (f > 0.0) f = floor(f+0.5);
   if (f < 0.0) f = ceil(f-0.5);

   if (!FIXABLE(f)) {
       return rb_dbl2big(f);
   }
   val = f;
   return LONG2FIX(val);
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.