From: Markus Date: 2004-10-15T02:55:19+09:00 Subject: Re: Rounding to X digits Here's mine (with a few extras): class Numeric def iff(cond) cond ? self : self-self end def to_the_nearest(n) n*(self/n).round end def aprox(x,n=0.001) (to_the_nearest n) == (x.to_the_nearest n) end def at_least(x); (self >= x) ? self : x; end def at_most(x); (self <= x) ? self : x; end end -- Markus On Thu, 2004-10-14 at 06:19, Eric Anderson wrote: > This seems like such a basic question yet I can't really find the answer > anywhere in the docs (I'm probably looking in the wrong place). > > Anyway I need to compute a percentage and output it. The percentage > should be in the form 39.45% (i.e. round to the nearest two decimal > places). So I have > > top = 68 > bottom = 271 > > percentage = (top.to_f / bottom * 100 * 100).round.to_f / 100 > > The above works but it does not seem very intuitive. What I would rather is: > > percentage = (top.to_f / bottom).round(4) * 100 > > But round does not take any arguments on how many decimal places I want. > It just assumes I don't want any. Perhaps there is another function that > I am not seeing that will round while keeping a certain number of > decimal places. Obviously I could also enhance round to take an optional > argument but I wanted to see if there was an already existing function > in the Ruby std library that will do it for me. > > Thanks, > > Eric >