I understand the numbers are non-negative. One can do the following:
Code
def floor_it(f, sig_digits=5)
pow = sprintf("%e", f)[-3..-1].to_i
(f *= 10**(-pow)).floor(sig_digits-1) * 10**(pow)
end
Examples
floor_it 0.007425742694 #=> 0.0074257
floor_it 3852.574257425742694 #=> 3852.5
Explanation
For
f = 385.74957425742694
sig_digits = 5
the steps are as follows. First express the number in scientific notation (as a string). See Kernel#sprintf.
a = sprintf("%e", f)
#=> "3.857496e+02"
We wish to extract the last two digits.
b = a[-3..-1]
#=> "02"
Convert that to an integer.
pow = b.to_i
#=> 2
Shift f
's decimal point so there is one non-zero digit to the left of the decimal point.
f *= 10**(-pow)
#=> 3.8574957425742697
Use the method Float#floor to obtain the desired digits.
d = f.floor(sig_digits-1)
#=> 3.8574957425742697.floor(4)
#=> 3.8574
Lastly, shift the decimal point back to its initial position.
d * 10**(pow)
#=> 385.74