On Tue, 1 Nov 2005, Harold Hausman wrote: > Alternatively there's this code from Phrogz's library ( > http://phrogz.net/rubylibs) which to me is more rubyish than sprintf. > Everytime you use sprintf, God kills a kitten. that quote is absolutely beautiful - though i __much__ prefer printf to cout ;-) > > -Harold > > #Code Follows: > > class Numeric > # Rounds to the specified number of decimal places, returning a string > value. > # > # (1.234).round_to(2) => '1.23' > # (-1.234).round_to(2) => '-1.23' > # (-0.007).round_to(2) => '-0.01' > # (-0.007).round_to(1) => '0.0' > def round_to(decimals) > if self<0 then > s='-'; > x=-self; > else > s=''; > x=self; > end > if x>=1.0e15 then > m=x.to_s; > else > m=(x*10**decimals).round.to_s > if (decimals!=0) then > k=m.length; > if k<=decimals then > z='000000000000000'[0..(decimals-k)] > m=z+m; > k=decimals+1; > end > m.insert(k-decimals,'.'); > end > end > s='' if (/^0\.0*$/=~m); > s+m; > end > end > > > On 10/31/05, i.v.r. <ivanvega / gmail.com> wrote: >> >> James Edward Gray II wrote: >>> On Oct 31, 2005, at 4:47 PM, i.v.r. wrote: >>> >>>> Hi, >>>> >>>> This seems like a simple task, yet I've been unable to accomplish it. >>>> Somewhere I read you could do: >>>> >>>> num.round(2).to_s("F") >>>> >>>> But that is not working, as the round method doesn't accept any >>>> parameters. >>>> >>>> Could someone help me figure this out? >>> >>>>> sprintf("%.2f", 1.012345) >>> => "1.01" >>>>> # ... or ... >>> ?> "%.2f" % 1.012345 >>> => "1.01" >>> >>> Hope that helps. >>> >>> James Edward Gray II >>> >>> >> That was fast! Thanks a lot. >> >> >> > -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | anything that contradicts experience and logic should be abandoned. | -- h.h. the 14th dalai lama ===============================================================================