From: "i.v.r." Date: 2005-11-02T05:43:35+09:00 Subject: Re: Newbie: How to format a number to always show two decimals? What's wrong with sprintf? I don't see how sprintf is evil versus the long procedure you detailed, but what do I know... I'm just a BASIC programmer, LOL. Ivan 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. > > -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. 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. >> >> >> >> > >