Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns self rounded to the nearest value with a precision of ndigits decimal digits.
When ndigits is negative, the returned value has at least ndigits.abs trailing zeros:
555.round(-1)      # => 560
555.round(-2)      # => 600
555.round(-3)      # => 1000
-555.round(-2)     # => -600
555.round(-4)      # => 0
Returns self when ndigits is zero or positive.
555.round     # => 555
555.round(1)  # => 555
555.round(50) # => 555
If keyword argument half is given, and self is equidistant from the two candidate values, the rounding is according to the given half value:
  • :up or nil: round away from zero:
    25.round(-1, half: :up)      # => 30
    (-25).round(-1, half: :up)   # => -30
    
  • :down: round toward zero:
    25.round(-1, half: :down)    # => 20
    (-25).round(-1, half: :down) # => -20
    
  • :even: round toward the candidate whose last nonzero digit is even:
    25.round(-1, half: :even)    # => 20
    15.round(-1, half: :even)    # => 20
    (-25).round(-1, half: :even) # => -20
    
Raises and exception if the value for half is invalid.
 
               static VALUE
int_round(int argc, VALUE* argv, VALUE num)
{
    int ndigits;
    int mode;
    VALUE nd, opt;

    if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
    ndigits = NUM2INT(nd);
    mode = rb_num_get_rounding_option(opt);
    if (ndigits >= 0) {
        return num;
    }
    return rb_int_round(num, ndigits, mode);
}
            

Was this page useful?