How do I always round a number down in Ruby?

7.1k Views Asked by At

For example, if I want 987 to equal "900".

2

There are 2 best solutions below

1
Cary Swoveland On BEST ANSWER
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
1
John C On

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.