From: Ara.T.Howard@... Date: 2004-10-16T00:14:30+09:00 Subject: Re: Rounding to X digits --8323328-351216961-1097852869=:30612 Content-Type: MULTIPART/MIXED; BOUNDARY="8323328-351216961-1097852869=:30612" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323328-351216961-1097852869=:30612 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE On Fri, 15 Oct 2004, trans. (T. Onoma) wrote: > On Thursday 14 October 2004 01:55 pm, Markus wrote: > | 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=3D0.001) > | (to_the_nearest n) =3D=3D (x.to_the_nearest n) > | end > | def at_least(x); (self >=3D x) ? self : x; end > | def at_most(x); (self <=3D x) ? self : x; end > | end > | > > | def to_the_nearest(n) > | n*(self/n).round > | end > def round_to_nearest( n=3D0.01 ) > =C2=A0=C2=A0 (self * (1/n)).round.to_f / (1/n) > =C2=A0=C2=A0end > > For some reason they don't give the exact same answer. Try an edge case. > > irb(main):066:0> 0.1 * (134.45/0.1).round > =3D> 134.4 > irb(main):067:0> (134.45 * (1/0.1)).round.to_f / (1/0.1) > =3D> 134.5 jib:~/eg/ruby > cat truncate.rb class Float def truncate sd =3D 2 i =3D self.to_i prec =3D 10 ** sd fraction =3D (i.zero? ? self : (self / i) - 1) i + (fraction * prec).to_i / prec.to_f end end p(0.1 * (134.45/0.1).truncate) #=3D> 134.4 p((134.45 * (1/0.1)).truncate.to_f / (1/0.1)) #=3D> 134.4 jib:~/eg/ruby > ruby truncate.rb 134.4 134.4 regards. -a -- =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | When you do something, you should burn yourself completely, like a good | bonfire, leaving no trace of yourself. --Shunryu Suzuki =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D --8323328-351216961-1097852869=:30612-- --8323328-351216961-1097852869=:30612--