Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Float#prev_float

float.prev_float → float

Returns the next-smaller representable Float.

These examples show the internally stored values (64-bit hexadecimal) for each Float f and for the corresponding f.pev_float:

Example
f = 5e-324   # 0x0000000000000001
f.prev_float # 0x0000000000000000

f = 0.01     # 0x3f847ae147ae147b
f.prev_float # 0x3f847ae147ae147a

In the remaining examples here, the output is shown in the usual way (result to_s):

Example
0.01.prev_float   # => 0.009999999999999998
1.0.prev_float    # => 0.9999999999999999
100.0.prev_float  # => 99.99999999999999

f = 0.01
(0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }

Output:

0 0x1.47ae147ae147bp-7 0.01
1 0x1.47ae147ae147ap-7 0.009999999999999998
2 0x1.47ae147ae1479p-7 0.009999999999999997
3 0x1.47ae147ae1478p-7 0.009999999999999995

Related: Float#next_float.

See also #positive? #quo #phase #rationalize also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0