Skip to content
instance method

Float#floor

() -> ::Integer
(::int digits) -> (::Integer | ::Numeric)
floor(ndigits = 0) → float or integer

Returns a float or integer that is a “floor” value for self, as specified by ndigits, which must be an integer-convertible object.

When self is zero, returns a zero value: a float if ndigits is positive, an integer otherwise:

Example
f = 0.0      # => 0.0
f.floor(20)  # => 0.0
f.floor(0)   # => 0
f.floor(-20) # => 0

When self is non-zero and ndigits is positive, returns a float with ndigits digits after the decimal point (as available):

Example
f = 12345.6789
f.floor(1)  # => 12345.6
f.floor(3)  # => 12345.678
f.floor(30) # => 12345.6789
f = -12345.6789
f.floor(1)  # => -12345.7
f.floor(3)  # => -12345.679
f.floor(30) # => -12345.6789

When self is non-zero and ndigits is non-positive, returns an integer value based on a computed granularity:

  • The granularity is 10 ** ndigits.abs.

  • The returned value is the largest multiple of the granularity that is less than or equal to self.

Examples with positive self:

ndigits Granularity 12345.6789.floor(ndigits)
0 1 12345
-1 10 12340
-2 100 12300
-3 1000 12000
-4 10000 10000
-5 100000 0

Examples with negative self:

ndigits Granularity -12345.6789.floor(ndigits)
0 1 -12346
-1 10 -12350
-2 100 -12400
-3 1000 -13000
-4 10000 -20000
-5 100000 -100000
-6 1000000 -1000000

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

Example
(0.3 / 0.1).floor  # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)

Related: Float#ceil.

See also #finite? #hash #fdiv #infinite? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0