End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Float#truncate
float.truncate([ndigits]) → integer or float
numeric.c
View on GitHub ↗
static VALUE
flo_truncate(int argc, VALUE *argv, VALUE num)
{
if (signbit(RFLOAT_VALUE(num)))
return flo_ceil(argc, argv, num);
else
return flo_floor(argc, argv, num);
}
Returns float truncated (toward zero) to 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 floating point number when ndigits is positive, otherwise returns an integer.
Example
2.8.truncate #=> 2 (-2.8).truncate #=> -2 1.234567.truncate(2) #=> 1.23 34567.89.truncate(-2) #=> 34500
Note that the limited precision of floating point arithmetic might lead to surprising results:
Example
(0.3 / 0.1).truncate #=> 2 (!)