views:

120

answers:

3

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?

+1  A: 

It looks a little ugly, but as a first shot (rounds up everytime) ...

>> (("230957".split("").first.to_i + 1).to_s + \
   ("0" * ("230957".size - 1))).to_i
=> 300000

Better (rounds correct):

>> (230957 / 10 ** Math.log10(230957).floor) * \
   10 ** Math.log10(230957).floor
=> 200000
The MYYN
+1  A: 
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
mikej
mikej, thanks for pointing out that my 'solution' wasn't rounding up. I deleted the entire solution to prevent confusion.
John
@John: I'd be interested in your solution, as I'm wanting something that'll round to the closest rather than round up.
Andrew Grimm
@Andrew if you change the condition in my method from `if remainder == 0` to `if remainder == 0 || remainder < divisor / 2` then it will round to the closest. If that isn't what you mean then if you post a separate question with some examples of what you want then I'll take a look.
mikej
A: 

I haven't actually done any coding in Ruby, but you would be able to do that with a standard rounding function if you pushed it over to the digit you wanted first.

Example:

230957 / 100000(the resolution you want) = 2.30957

Round 2.30957 = 2, or Round to Ceiling/Round value + 0.5 to get it to go to the upper value rather than the lower.

2 or 3 * 100000(the resolution you want) = 200000 or 300000 respectively.

Hope this helps!

Lunin