Jesse McCann
Jesse McCann

Reputation: 55

How do I always round a number down in Ruby?

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

Upvotes: 5

Views: 7313

Answers (2)

John C
John C

Reputation: 4396

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.

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110685

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

Upvotes: 16

Related Questions