我试图定义一个函数,它尊重以下四舍五入条件(整到最接近的整数或十分之一):

我发现的主要问题是关于负数的舍入。
下面是我的实现(对于条件检查很抱歉,但这个示例就是这样):
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我不是百分之百肯定什么是最好的方法来舍入负数。
谢谢!
发布于 2019-02-22 14:29:34
在文档中,您可以使用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的链接)支持其中,但这不是其中之一。
https://stackoverflow.com/questions/54828641
复制相似问题