instance method
Rational#round
(?half: :up | :down | :even) -> ::Integer
(::Integer digits, ?half: :up | :down | :even) -> (::Integer | ::Rational)
rat.round([ndigits] [, half: mode]) → integer or rational
rational.c
View on GitHub ↗
static VALUE
nurat_round_n(int argc, VALUE *argv, VALUE self)
{
VALUE opt;
enum ruby_num_rounding_mode mode = (
argc = rb_scan_args(argc, argv, "*:", NULL, &opt),
rb_num_get_rounding_option(opt));
VALUE (*round_func)(VALUE) = ROUND_FUNC(mode, nurat_round);
return f_round_common(argc, argv, self, round_func);
}
Returns rat rounded to the nearest value with a precision of ndigits decimal digits (default: 0).
When the precision is negative, the returned value is an integer with at least ndigits.abs trailing zeros.
Returns a rational when ndigits is positive, otherwise returns an integer.
Example
Rational(3).round #=> 3 Rational(2, 3).round #=> 1 Rational(-3, 2).round #=> -2 # decimal - 1 2 3 . 4 5 6 # ^ ^ ^ ^ ^ ^ # precision -3 -2 -1 0 +1 +2 Rational('-123.456').round(+1).to_f #=> -123.5 Rational('-123.456').round(-1) #=> -120
The optional half keyword argument is available similar to Float#round.
Example
Rational(25, 100).round(1, half: :up) #=> (3/10) Rational(25, 100).round(1, half: :down) #=> (1/5) Rational(25, 100).round(1, half: :even) #=> (1/5) Rational(35, 100).round(1, half: :up) #=> (2/5) Rational(35, 100).round(1, half: :down) #=> (3/10) Rational(35, 100).round(1, half: :even) #=> (2/5) Rational(-25, 100).round(1, half: :up) #=> (-3/10) Rational(-25, 100).round(1, half: :down) #=> (-1/5) Rational(-25, 100).round(1, half: :even) #=> (-1/5)