Printing Left-Justified Values in Fortran

July 31, 2011

By default, Fortran right-justifies numerical and string output when printing to the screen or to a file. For example, the following code

integer :: i = 42
real :: r = 46.2
print '(3a8)', 'String', 'Integer', 'Real'
print '(a8,i8,f8.2)', 'Label', i, r

produces

  String Integer    Real
   Label      42   46.20

One approach to left-align the CHARACTER literals above is to simply add the appropriate number of spaces to shift them to the left, making each exactly eight characters long:

print '(3a8)', 'String  ', 'Integer ', 'Real    '
print '(a8,i8,f8.2)', 'Label:  ', i, r

Alternatively, storing them in CHARACTER variables of the appropriate length will also work:

character(len=8), dimension(3) :: header = (/ 'String ', 'Integer', 'Real   ' /)
character(len=8) :: c = 'Label:'
print '(3a8)', header
print '(a8,i8,f8.2)', c, i, r

Both of these methods yield the following output:

String  Integer Real
Label         42   46.20

But the numerical values are not left-justified (although it’s hard to tell from above without counting characters since there is no surrounding output).

For numerical values, the usual approach is to use an internal write to first write the formatted values to character strings of length eight, and then print the left-justified strings.

character(len=8) :: i_char, r_char
write (i_char, '(i8)') i
write (r_char, '(f8.2)') r
print '(3a8)', c, adjustl(i_char), adjustl(r_char)

This produces the following output, with all fields being left justified:

String  Integer Real
Label   42      46.20

Note that this method makes use of the ADJUSTL intrinsic introduced in Fortran 90. Internal writes can also be used in FORTRAN 77 to achieve the same result, but with a little more work to carry out the steps performed by ADJUSTL.

See leftjust.f90 for code used in the examples above.