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?
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?
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
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
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.
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!