5

我想将数字四舍五入到最接近的数量级。(我想我说的对)

这里有些例子:

Input => Output

8 => 10
34 => 40
99 => 100
120 => 200
360 => 400
990 => 1000
1040 => 2000
1620 => 2000
5070 => 6000
9000 => 10000

有人知道用 Ruby 或 Rails 快速编写它的方法吗?

本质上,我需要知道数字的数量级以及如何按该精度四舍五入。

谢谢!

4

2 回答 2

14

这是另一种方式:

def roundup(num)
  x = Math.log10(num).floor
  num=(num/(10.0**x)).ceil*10**x
  return num
end

更通俗地说:

def roundup(num)
  x = Math.log10(num).floor
  (num/(10.0**x)).ceil * 10**x
end
于 2009-05-18T00:30:55.807 回答
0

这是一个解决方案。它执行以下规则:

  • 不修改 0 和 10 的幂;
  • 9???向上取整到 10000(无论多长时间);
  • 一种???向上舍入到 B000(无论多长),其中 B 是 A 后面的数字。

.

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
于 2009-05-18T00:24:08.367 回答