计算ruby的百分比?
是否有任何方法可用于计算铁轨或ruby的百分比?
编辑:
我正在寻找像…这样的function
100000.percent(10)
将返回10000
。
100000
是值..(值是BigDecimal
) 10 %
..
result = 100000 * 10 / 100
result = 10000
..
你的意思是这个percentage = a/b*100
?
根据您的新说明进行更新 :
class Numeric def percent_of(n) self.to_f / n.to_f * 100.0 end end # Note: the brackets () around number are optional p (1).percent_of(10) # => 10.0 (%) p (200).percent_of(100) # => 200.0 (%) p (0.5).percent_of(20) # => 2.5 (%) pizza_slices = 5 eaten = 3 p eaten.percent_of(pizza_slices) # => 60.0 (%)
基于Mladen的代码。
有一种方法。 这里是:
class Numeric def percents self * 100 end end 0.56.percents => 56.0