更好的 Ruby 实现,将小数四舍五入到最接近的 0.5
这看起来效率低得可怕。有人可以给我一个更好的 Ruby 方法吗?
def round_value
x = (self.value*10).round/10.0 # rounds to two decimal places
r = x.modulo(x.floor) # finds remainder
f = x.floor
self.value = case
when r.between?(0, 0.25)
f
when r.between?(0.26, 0.75)
f+0.5
when r.between?(0.76, 0.99)
f+1.0
end
end
This seems horrible inefficient. Can someone give me a better Ruby way.
def round_value
x = (self.value*10).round/10.0 # rounds to two decimal places
r = x.modulo(x.floor) # finds remainder
f = x.floor
self.value = case
when r.between?(0, 0.25)
f
when r.between?(0.26, 0.75)
f+0.5
when r.between?(0.76, 0.99)
f+1.0
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个经典问题:这意味着您正在使用不同的基数进行整数舍入。您可以将“2”替换为任何其他数字。
A classic problem: this means you're doing integer rounding with a different radix. You can replace '2' with any other number.
将数字乘以二。
四舍五入到整数。
除以二。
在一般形式中,您可以乘以每个整数所需的档位数(假设四舍五入到 0.2 就是每个整数值 5 个档位)。然后圆形;然后除以相同的值。
Multiply the number by two.
round to whole number.
Divide by two.
In a generalized form, you multiply by the number of notches you want per whole number (say round to .2 is five notches per whole value). Then round; then divide by the same value.
您也可以使用
取模
运算符来完成此操作。如果 x = 1234.56,这将返回 1234.6
我偶然发现了这个答案,因为我正在编写一个基于 Ruby 的计算器,并且它使用 Ruby 的 Money 库来完成所有财务计算。 Ruby Money 对象不具有与 Integer 或 Float 相同的舍入函数,但它们可以返回余数(例如模、
%
)。因此,使用 Ruby Money,您可以通过以下方式将 Money 对象四舍五入到最接近的 $25:
这里,如果 x = $1234.45 (<#Moneyfractional:123445currency:USD>),那么它将返回 $1250.00 (#
注意:没有需要使用 Ruby Money 对象进行舍入,因为该库会为您处理它!
You can accomplish this with a
modulo
operator too.If x = 1234.56, this will return 1234.6
I stumbled upon this answer because I am writing a Ruby-based calculator and it used Ruby's Money library to do all the financial calculations. Ruby Money objects do not have the same rounding functions that an Integer or Float does, but they can return the remainder (e.g. modulo,
%
).Hence, using Ruby Money you can round a Money object to the nearest $25 with the following:
Here, if x = $1234.45 (<#Money fractional:123445 currency:USD>), then it will return $1250.00 (#
NOTE: There's no need to round with Ruby Money objects since that library takes care of it for you!