From: hmmm Date: 2005-11-16T09:14:30+09:00 Subject: Re: Quick question. ------=_Part_14717_8224140.1132100067710 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline How would I format a number to simply be left-zero-padded with 2 floating points? eg. 000.24 from .238888888 001.24 from 1.237777777 010.25 from 10.249999999 100.25 from 100.24999999 I can do: %.2f to get the 2 decimals, but it doesn't do left-zero-pad. I can do: %03d to pad 3 digits to the left, but it doesn't trim the decimal= s I can do: printf("%03d%.2f", val, (val.to_f-val.to_i)) but that always injects an extra 0 like so: 0000.24 0010.24 0100.25 1000.25 I have yet to find a good (useful) doc on how the format args work, so poin= t me there but beware that most of the docs out there are super useless :) -henry On 9/13/05, Gavin Kistner wrote: > > On Sep 13, 2005, at 7:22 AM, Brian Schr=F6der wrote: > > Or you can use the % operator on a string which I like better. I.e. > > "%3.2f" % 1.0 #=3D> " 1.00" > > Just remember that if you have multiple formatted pieces in the same > string, you need to supply the argument to the #% method as an array: > > m =3D 57.23562 > s =3D 83.333333 > "%3.2f - %3.2f =3D %3.2f" % [ m, s, m-s ] > > #=3D> "57.24 - 83.33 =3D -26.10" > > > The fun comes when you use string interpolation along with sprintf's > codes: > > class Numeric > def rounded_to( decimals ) > decimals =3D decimals.round > if decimals < 0 > factor =3D 10.0 ** -decimals > ( ( self / factor ).round * factor ).round.to_s > else > "%.#{decimals}f" % self > end > end > end > > [ 1, -1, 0.017, -0.017, 1254, -81.2412234 ].each{ |number| > [5,2,1,0,-1,-2,-3].each{ |decimal_places| > puts number.rounded_to( decimal_places ) > } > puts '-' * 40 > } > > > 1.00000 > 1.00 > 1.0 > 1 > 0 > 0 > 0 > ---------------------------------------- > -1.00000 > -1.00 > -1.0 > -1 > 0 > 0 > 0 > ---------------------------------------- > 0.01700 > 0.02 > 0.0 > 0 > 0 > 0 > 0 > ---------------------------------------- > -0.01700 > -0.02 > -0.0 > -0 > 0 > 0 > 0 > ---------------------------------------- > 1254.00000 > 1254.00 > 1254.0 > 1254 > 1250 > 1300 > 1000 > ---------------------------------------- > -81.24122 > -81.24 > -81.2 > -81 > -80 > -100 > 0 > ---------------------------------------- > > > -- john hager ------------------------------------- netcam@gmail.com url: http://www.orgo.com cell: 619.261.5990 ------=_Part_14717_8224140.1132100067710--