首页 > 解决方案 > Ruby 舍入约定

问题描述

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

在此处输入图像描述

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

这是我的实现(对不起条件检查,但仅适用于此示例):

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

谢谢!

标签: ruby-on-railsrubyrounding

解决方案


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


推荐阅读