From: Harold Hausman Date: 2005-11-01T09:21:35+09:00 Subject: Re: Newbie: How to format a number to always show two decimals? ------=_Part_9875_4065111.1130804492474 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline 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) =3D> '1.23' # (-1.234).round_to(2) =3D> '-1.23' # (-0.007).round_to(2) =3D> '-0.01' # (-0.007).round_to(1) =3D> '0.0' def round_to(decimals) if self<0 then s=3D'-'; x=3D-self; else s=3D''; x=3Dself; end if x>=3D1.0e15 then m=3Dx.to_s; else m=3D(x*10**decimals).round.to_s if (decimals!=3D0) then k=3Dm.length; if k<=3Ddecimals then z=3D'000000000000000'[0..(decimals-k)] m=3Dz+m; k=3Ddecimals+1; end m.insert(k-decimals,'.'); end end s=3D'' if (/^0\.0*$/=3D~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) > > =3D> "1.01" > > >> # ... or ... > > ?> "%.2f" % 1.012345 > > =3D> "1.01" > > > > Hope that helps. > > > > James Edward Gray II > > > > > That was fast! Thanks a lot. > > > ------=_Part_9875_4065111.1130804492474--