Instance method
# round
Returns self rounded to the nearest value with a precision of ndigits decimal digits.
How to use
Quick guide
Official content
Official how?
I scraped all this data from the official documentation. I created this site to make it easier for beginners and more pleasant for professionals to use Ruby.
Georgie boy
Creator of ruby-docs.org
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
ornil
: 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.Related:
Integer#truncate
.
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?
Leave your feedback
Please hit 'submit' to confirm your feedback.
Leave your feedback
Please hit 'submit' to confirm your feedback.