End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Float#rationalize
flt.rationalize([eps]) → rational
rational.c
View on GitHub ↗
static VALUE
float_rationalize(int argc, VALUE *argv, VALUE self)
{
double d = RFLOAT_VALUE(self);
VALUE rat;
int neg = d < 0.0;
if (neg) self = DBL2NUM(-d);
if (rb_check_arity(argc, 0, 1)) {
rat = rb_flt_rationalize_with_prec(self, argv[0]);
}
else {
rat = rb_flt_rationalize(self);
}
if (neg) RATIONAL_SET_NUM(rat, rb_int_uminus(RRATIONAL(rat)->num));
return rat;
}
Returns a simpler approximation of the value (flt-|eps| <= result <= flt+|eps|). If the optional argument eps is not given, it will be chosen automatically.
Example
0.3.rationalize #=> (3/10) 1.333.rationalize #=> (1333/1000) 1.333.rationalize(0.01) #=> (4/3)
See also Float#to_r.