Ruby四舍五入约定

时间:2019-02-22 13:55:24

标签: ruby-on-rails ruby rounding

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

enter image description here

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

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

  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%舍入负数的最佳方法是什么。

谢谢!

1 个答案:

答案 0 :(得分:6)

在文档中,您可以使用Integer#round(和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核心库支持(请参见上面的docs链接),但这不是其中之一。