From: "David A. Black" Date: 2005-11-01T09:41:13+09:00 Subject: Re: Newbie: How to format a number to always show two decimals? Hi -- 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. > > -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 Aside to Phrogz: is that left over from a game of code golf?? :-) David -- David A. Black dblack@wobblini.net