Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I always round a number down in Ruby?

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

like image 649
Jesse McCann Avatar asked Dec 08 '22 17:12

Jesse McCann


2 Answers

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
like image 85
Cary Swoveland Avatar answered Dec 24 '22 11:12

Cary Swoveland


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.

like image 41
John C Avatar answered Dec 24 '22 09:12

John C