Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round numbers up to a dynamic precision in Ruby On Rails?

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!

like image 591
Tony Avatar asked May 17 '09 23:05

Tony


1 Answers

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
like image 82
BernzSed Avatar answered Nov 15 '22 04:11

BernzSed