Reputation: 19181
I want to round numbers up to their nearest order of magnitude. (I think I said this right)
Here are some examples:
Input => Output
8 => 10
34 => 40
99 => 100
120 => 200
360 => 400
990 => 1000
1040 => 2000
1620 => 2000
5070 => 6000
9000 => 10000
Anyone know a quick way to write that in Ruby or Rails?
Essentially I need to know the order of magnitude of the number and how to round by that precision.
Thanks!
Upvotes: 5
Views: 3085
Reputation: 1139
Here's another way:
def roundup(num)
x = Math.log10(num).floor
num=(num/(10.0**x)).ceil*10**x
return num
end
More idiomatically:
def roundup(num)
x = Math.log10(num).floor
(num/(10.0**x)).ceil * 10**x
end
Upvotes: 15
Reputation: 87391
Here is a solution. It implements the following rules:
.
def roundup(n)
n = n.to_i
s = n.to_s
s =~ /\A1?0*\z/ ? n : s =~ /\A\d0*\z/ ? ("1" + "0" * s.size).to_i :
(s[0, 1].to_i + 1).to_s + "0" * (s.size - 1)).to_i
end
fail if roundup(0) != 0
fail if roundup(1) != 1
fail if roundup(8) != 10
fail if roundup(34) != 40
fail if roundup(99) != 100
fail if roundup(100) != 100
fail if roundup(120) != 200
fail if roundup(360) != 400
fail if roundup(990) != 1000
fail if roundup(1040) != 2000
fail if roundup(1620) != 2000
fail if roundup(5070) != 6000
fail if roundup(6000) != 10000
fail if roundup(9000) != 10000
Upvotes: 0