Method: Integer#round
- Defined in:
- numeric.c
#round(ndigits = 0, half: :up) ⇒ Integer
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:
-
:upornil: 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.
5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 |
# File 'numeric.c', line 5780
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);
}
|