Ruby 舍入约定

Ruby Rounding Convention

我正在尝试定义一个符合以下舍入条件的函数(舍入到最接近的整数或十分之一):

我发现的主要问题是四舍五入负数。

这是我的实现(对于条件检查很抱歉,但它仅适用于此示例):

  def convention_round(number, to_int = false)
    if to_int
      number.round
    else
      number.round(1)
    end
  end

  convention_round(1.2234) # 1.2
  convention_round(1.2234, true) # 1

  convention_round(1.896) # 1.9
  convention_round(1.896, true) # 2

  convention_round(1.5) # 1.5
  convention_round(1.5, true) # 2

  convention_round(1.55) # 1.6
  convention_round(1.55, true) # 2

  convention_round(-1.2234) # -1.2
  convention_round(-1.2234, true) # -1

  convention_round(-1.896) # -1.9
  convention_round(-1.2234, true) # -2

  convention_round(-1.5) # -1.5
  convention_round(-1.5, true) # -2 (Here I want rounded to -1)

  convention_round(-1.55) # -1.6 (Here I want rounded to -1.5)
  convention_round(-1.55, true) # -2

我不是 100% 确定舍入负数的最佳方法是什么。

谢谢!

从文档中,您可以为此使用 Integer#round (and Float#round),如下所示:

def convention_round(number, precision = 0)
  number.round(
    precision,
    half: (number.positive? ? :up : :down)
  )
end

convention_round(1.4)      #=> 1
convention_round(1.5)      #=> 2
convention_round(1.55)     #=> 2
convention_round(1.54, 1)  #=> 1.5
convention_round(1.55, 1)  #=> 1.6

convention_round(-1.4)      #=> -1
convention_round(-1.5)      #=> -1 # !!!
convention_round(-1.55)     #=> -2
convention_round(-1.54, 1)  #=> -1.55
convention_round(-1.55, 1)  #=> -1.5 # !!!

这不完全是您要求的方法签名,但它是一种更通用的形式 - 因为您可以提供任意精度。

但是,我想指出具有讽刺意味的是(尽管有方法名称)这不是一种传统的舍入数字的方法。

有一些不同的约定,ruby 核心库支持所有(?)约定(参见上面的 link 文档),但这不是其中之一。