Ruby 如何将整数舍入到<;最近大数>;用红宝石?

Ruby 如何将整数舍入到<;最近大数>;用红宝石?,ruby,rounding,significant-digits,Ruby,Rounding,Significant Digits,假设我有以下任何一个数字: 230957或 83487或 4785 在Ruby中,我可以用什么方式返回它们 300000或 90000或 分别是5000美元 它看起来有点难看,但作为第一枪(每次都会出现) 更好(正确): 举个例子: irb(main):022:0> round_up(4785) => 5000 irb(main):023:0> round_up(83487) => 90000 irb(main):024:0> round_up(230957

假设我有以下任何一个数字:

230957或 83487或 4785

在Ruby中,我可以用什么方式返回它们 300000或 90000或
分别是5000美元

它看起来有点难看,但作为第一枪(每次都会出现)

更好(正确):

举个例子:

irb(main):022:0> round_up(4785)
=> 5000    
irb(main):023:0> round_up(83487)
=> 90000
irb(main):024:0> round_up(230957)
=> 300000

实际上,我还没有用Ruby做过任何编码,但是如果你先把它推到你想要的数字,你就可以用一个标准的舍入函数来做

例如:

230957 / 100000(the resolution you want) = 2.30957
舍入
2.30957=2
,或舍入到上限/舍入值
+0.5
,使其转到上限值而不是下限值

2 or 3 * 100000(the resolution you want) = 200000 or 300000 respectively.
希望这有帮助

def round_to_significant_digit(i, significant_digits = 1)
  exp = Math.log10(i).floor - (significant_digits - 1)
  (i / 10.0 ** exp).round * 10 ** exp
end

 >> [230957, 83487, 4785].collect{|i|round_to_significant_digit(i)}
 => [200000, 80000, 5000]
额外学分:

 >>  [230957, 83487, 4785].collect{|i|round_to_significant_digit(i, 2)}
 => [230000, 83000, 4800]
 >>  [230957, 83487, 4785].collect{|i|round_to_significant_digit(i, 3)}
 => [231000, 83500, 4790]

在Rails中,您可能还喜欢“number_to_human”助手,它会自动选择一个好的维度进行舍入


Math.round接受负数。如果您只查找最接近的10,则可以执行
(my_num).round(-1)

唯一的缺点是这里无法合并ceil,因此它并不总是四舍五入--
4。四舍五入(-1)
将返回0。

一个简单的建议:

def nearest_large_number value
  str = value.to_s.gsub(/^([0-9])/) { "#{$1}." }
  multiplicator = ("1" + "0" * str.split('.')[1].length).to_i
  str.to_f.ceil * multiplicator
end
要使用它:

nearest_large_number 230957
=> 300000
以下是我的版本:

def round(num, nearest = nil, pivot = nil)
  negative = num < 0
  num = -num if negative
  precision = Math.log10(num).to_i rescue 1
  nearest ||= precision == 0 ? 10 : 10**precision
  pivot ||= nearest
  result = (num + pivot) / nearest * nearest
  negative ? -result : result
end

mikej,谢谢你指出我的“解决方案”不是取整。为了避免混淆,我删除了整个解决方案。@John:我对你的解决方案感兴趣,因为我想要的是取整到最接近的值,而不是取整到最接近的值。@Andrew如果您将我方法中的条件从
如果余数==0
更改为
如果余数==0 | |余数
,那么它将取整到最接近的值。如果这不是你的意思,那么如果你发布一个单独的问题,并举例说明你想要什么,那么我会看一看。
def nearest_large_number value
  str = value.to_s.gsub(/^([0-9])/) { "#{$1}." }
  multiplicator = ("1" + "0" * str.split('.')[1].length).to_i
  str.to_f.ceil * multiplicator
end
nearest_large_number 230957
=> 300000
def round(num, nearest = nil, pivot = nil)
  negative = num < 0
  num = -num if negative
  precision = Math.log10(num).to_i rescue 1
  nearest ||= precision == 0 ? 10 : 10**precision
  pivot ||= nearest
  result = (num + pivot) / nearest * nearest
  negative ? -result : result
end
round(0)   # 0
round(1)   # 10
round(9)   # 10
round(10)  # 20
round(-10) # -20
round(100) # 1000

round(1, 1000)        # 1000
round(499, 1000, 500) # 0
round(500, 1000, 500) # 1000