How do I round an integer up to <nearest large number> in Ruby?

John picture John · Aug 3, 2010 · Viewed 6.9k times · Source

Say I have any of the following numbers:

230957 or 83487 or 4785

What is a way in Ruby I could return them as 300000 or 90000 or 5000, respectively?

Answer

mikej picture mikej · Aug 3, 2010
def round_up(number)
  divisor = 10**Math.log10(number).floor
  i = number / divisor
  remainder = number % divisor
  if remainder == 0
    i * divisor
  else
    (i + 1) * divisor
  end
end

With your examples:

irb(main):022:0> round_up(4785)
=> 5000    
irb(main):023:0> round_up(83487)
=> 90000
irb(main):024:0> round_up(230957)
=> 300000