Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage in ruby? [closed]

Tags:

ruby

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

like image 549
krunal shah Avatar asked Sep 08 '10 13:09

krunal shah


People also ask

How do you find the percentage in Ruby?

percent_of(200) = 100. So for my case n. to_f * self. to_f / 100.0 works.


1 Answers

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.

like image 95
randomguy Avatar answered Oct 07 '22 13:10

randomguy