开发者

Calculate percentage in ruby? [closed]

开发者 https://www.devze.com 2023-01-15 21:34 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

Is there any method available to calculate percentage in rails or ruby ??

EDIT:

I am looking for a function like ..

100000.percent(10) will return me 10000.开发者_高级运维

100000 is value ..(value is BigDecimal) 10 % ..

result = 100000 * 10 / 100

result = 10000 ..


You mean like this percentage = a/b*100?

Update based on your new description:

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 (%)

Based on Mladen's code.


There is a method. Here it is:

class Numeric
  def percents
    self * 100
  end
end

0.56.percents
=> 56.0
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号