这似乎是可怕的低效。谁能给我一个更好的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
发布于 2010-10-01 15:25:45
class Float
def round_point5
(self * 2).round / 2.0
end
end
一个经典的问题:这意味着你正在用一个不同的基数进行整数舍入。您可以将“2”替换为任何其他数字。
发布于 2010-10-01 15:25:28
将这个数字乘以2。
四舍五入为整数。
除以2。
(x * 2.0).round / 2.0
在一般形式中,您可以乘以每个整数所需的刻度数(假设舍入到.2是每个整数的五个刻度)。然后四舍五入;然后除以相同的值。
(x * notches).round / notches
发布于 2017-03-28 11:10:46
您也可以使用modulo
操作符来完成此操作。
(x + (0.05 - (x % 0.05))).round(2)
如果x= 1234.56,则返回1234.6
我偶然发现了这个答案,因为我正在编写一个基于Ruby的计算器,它使用Ruby的钱库来进行所有的财务计算。Ruby Money对象没有Integer或Float对象那样的舍入函数,但它们可以返回余数(例如模数、%
)。
因此,使用Ruby Money可以将Money对象舍入为最接近的$25,如下所示:
x + (Money.new(2500) - (x % Money.new(2500)))
这里,如果x= $1234.45 (<#Money分数:123445 currency:USD>),则它将返回$1250.00 (#
注意:没有必要去处理Ruby Money对象,因为这个库会帮你处理它!
https://stackoverflow.com/questions/3837182
复制相似问题