tags:

views:

160

answers:

2

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 ..

+8  A: 

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 (ie. (1)) 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.

randomguy
@randomguy But is there any method available for this ??
krunal shah
@krunal no there is none.
Hugo
you can use the `:/` method: `a.to_f.send(:/, b).send(:*,100)` furthermore, this question makes me feel `:/`
John Douthat
Is it work if my value is in BigDecimal ??
krunal shah
@randomguy: Hey, thanks for the credits, it's really nice to have an effort of such magnitude recognized! :o)
Mladen Jablanović
@Mladen: Thanks for the sarcasm. I need it, House is still on break. :<
randomguy
A: 

There is a method. Here it is:

class Numeric
  def percents
    self * 100
  end
end

0.56.percents
=> 56.0
Mladen Jablanović
@Mladen i want a method something like .. 100000.percent(10) will return me 10000.
krunal shah
@krunal Then you want `100000 * .1`. You don't want a method.
meagar