Search code examples
fortrangfortran

Format descriptors with zero width, like F0.6 or G0.8


Standard documentation of fortran format specifiers explains how you can control most formats with two parameters, generally referred to as w and d. For example, a format specifier of Fw.d means a number will print out with a width of w characters (including the decimal) and d digits to the right of the decimal point. The G format is similar, except d is interpreted as the number of significant digits to print.

All of the documentation I've found so far uses examples where w is > 0, but I recently learned here that you can use a zero for the width parameter in a format specifier, which can be really nice for something like CSV output. It seems that w=0 is interpreted as "variable width" and you get as much or as little space as you need, to satisfy the d parameter (which gives decimal places for the F format and significant digits for the G format). For example, here's the F format with different values (and "b" indicates a blank character):

! tested with gfortran 5.5 on linux

print '(F8.3)', 7.777   ! prints bbb7.777
print '(F4.3)', 7.777   ! prints ****
print '(F0.3)', 7.777   ! prints 7.777

That all seems to make sense. G is a little more confusing to me in that G8.3 doesn't have any blanks and I don't know why G4.3 fails, but here it is in any event:

print '(G8.3)', 7.777   ! prints 7.78
print '(G4.3)', 7.777   ! prints ****
print '(G0.3)', 7.777   ! prints 7.78

My question is whether my understanding via trial and error is correct, whether this is documented anywhere, and whether it is part of the Fortran standard(s), or is it implementation specific?

(I spent a lot of time googling for this info but couldn't find anything, perhaps because I couldn't figure out what search terms to use.)


Solution

  • Yes, it is the standard Fortran behaviour. Fortran 2018 version (N2146 13.7.2.1 (6)):

    On output, with I, B, O, Z, D, E, EN, ES, EX, F, and G editing, the specified value of the field width w may be zero. In such cases, the processor selects the smallest positive actual field width that does not result in a field filled with asterisks. The specified value of w shall not be zero on input.

    There is also the G0 generalized editing (F2018 13.7.5) that can be used for any of the mentioned intrinsic datatypes and was introduced in Fortran 2008. It includes all the numeric types and also logical (L1) and character (A).