From: Robert Klemme Date: 2004-05-24T17:38:44+09:00 Subject: Re: Fortran Format? "Mark Sparshatt" schrieb im Newsbeitrag news:40ABD8AF.6020500@yahoo.co.uk... > Qubert wrote: > > >OK, I have an algorithm that I created to format a series of numbers > >for a column centric FORTRAN routine to use. I don't like what I have > >created, although it works, so I would like to ask if anyone here has > >a more cleaver way. > > > >Problem: I have a series of numbers that need to be formated as a > >FORTRAN program would. That is, FORTRAN cares more about columns than > >numbers so I need to fake the output of Ruby to make it look "decimal > >justified". > > > >Example, a series of numbers: > >3.15, 122.5, 303.123, 55.0 > >Input for C or Ruby (the space means a new number): > >3.15 122.5 > >303.123 55.0 > >Input needed for FORTRAN with format (f7.3,f5.1): > > 3.150122.5 > >303.123 55.0 > > > >My Ruby hack to put spaces at the begining if necessary: > >def ff(num,len1,len2) > > x = num.to_s.split(".") > > numstring = "" > > x[0].size.upto(len1 - 1) {|b| numstring << ' '} > > numstring << x[0] << "." > > numstring << x[1][0..len2] > >end > > > >code... > >bla ... > >printf("%s %s\n", ff(3.150,3,3),ff(122.5,3,1) > >printf("%s %s\n", ff(303.123,3,3),ff(55.0,3,1) > > > > > > > A better way would be to be to use the sprintf method (documented on > page 427 of the pickaxe) to format the string. > > The following code does what you want > > def ff(num, len1, len2) > sprintf("%#{len1 + len2 + 1}.#{len2}f", num) > end sprintf can already handle widths as arguments: sprintf( "%*.*f", len1 + len2, len2, num ) > printf("%s %s\n", ff(3.150,3,3),ff(122.5,3,1)) > printf("%s %s\n", ff(303.123,3,3),ff(55.0,3,1)) >> printf "%*.*f %*.*f\n", 7, 3, 3.150, 5, 1, 122.5 3.150 122.5 :-) robert > > > >I know that this needs improvement so your help would be appreciated. > >I have to interface with these types of FORTRAN programs a lot, thus > >far I have avoided this. > > > > > HTH > > -- > > Mark Sparshatt > >