计算红宝石的百分比? [英] Calculate percentage in ruby?
本文介绍了计算红宝石的百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何方法可以计算 rails 或 ruby 中的百分比??
Is there any method available to calculate percentage in rails or ruby ??
我正在寻找类似 .. 的函数
I am looking for a function like ..
100000.percent(10)
将返回给我 10000
.
100000
是值 ..(值是 BigDecimal
)10%
..
100000
is value ..(value is BigDecimal
)
10 %
..
结果 = 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 的代码.
Based on Mladen's code.
这篇关于计算红宝石的百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文