For example, if I want 987 to equal "900".
n = 987
m = 2
n.floor(-m)
#=> 900
See Integer#floor: "When the precision is negative, the returned value is an integer with at least ndigits.abs
trailing zeros."
or
(n / 10**m) * 10**m
#=> 900
You can use logarithms to calculate the best multiple to divide by.
def round_down(n)
log = Math::log10(n)
multip = 10 ** log.to_i
return (n / multip).to_i * multip
end
[4, 9, 19, 59, 101, 201, 1500, 102000].each { |x|
rounded = round_down(x)
puts "#{x} -> #{rounded}"
}
Result:
4 -> 4
9 -> 9
19 -> 10
59 -> 50
101 -> 100
201 -> 200
1500 -> 1000
102000 -> 100000
This trick is very handy when you need to calculate even tick spacings for graphs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With