Method: Float#floor

Defined in:
numeric.c

#floor([ndigits]) ⇒ Integer, Float

Returns the largest number less than or equal to float 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 floating point number when ndigits is positive, otherwise returns an integer.

1.2.floor      #=> 1
2.0.floor      #=> 2
(-1.2).floor   #=> -2
(-2.0).floor   #=> -2

1.234567.floor(2)   #=> 1.23
1.234567.floor(3)   #=> 1.234
1.234567.floor(4)   #=> 1.2345
1.234567.floor(5)   #=> 1.23456

34567.89.floor(-5)  #=> 0
34567.89.floor(-4)  #=> 30000
34567.89.floor(-3)  #=> 34000
34567.89.floor(-2)  #=> 34500
34567.89.floor(-1)  #=> 34560
34567.89.floor(0)   #=> 34567
34567.89.floor(1)   #=> 34567.8
34567.89.floor(2)   #=> 34567.89
34567.89.floor(3)   #=> 34567.89

Note that the limited precision of floating point arithmetic might lead to surprising results:

(0.3 / 0.1).floor  #=> 2 (!)


1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
# File 'numeric.c', line 1936

static VALUE
flo_floor(int argc, VALUE *argv, VALUE num)
{
    double number, f;
    int ndigits = 0;

    if (rb_check_arity(argc, 0, 1)) {
	ndigits = NUM2INT(argv[0]);
    }
    number = RFLOAT_VALUE(num);
    if (number == 0.0) {
	return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
    }
    if (ndigits > 0) {
	int binexp;
	frexp(number, &binexp);
	if (float_round_overflow(ndigits, binexp)) return num;
	if (number > 0.0 && float_round_underflow(ndigits, binexp))
	    return DBL2NUM(0.0);
	f = pow(10, ndigits);
	f = floor(number * f) / f;
	return DBL2NUM(f);
    }
    else {
	num = dbl2ival(floor(number));
	if (ndigits < 0) num = rb_int_floor(num, ndigits);
	return num;
    }
}