How can I left-justify numerical output in fortran?
Solution 1
There's not a particularly beautiful way. However, using an internal WRITE statement to convert the number to a text string (formerly done with an ENCODE statement), and then manipulating the text may do what you need.
Quoting http://rsusu1.rnd.runnet.ru/develop/fortran/prof77/node168.html
An internal file WRITE is typically used to convert a numerical value to a character string by using a suitable format specification, for example:
CHARACTER*8 CVAL RVALUE = 98.6 WRITE(CVAL, '(SP, F7.2)') RVALUE
The WRITE statement will fill the character variable CVAL with the characters ' +98.60 ' (note that there is one blank at each end of the number, the first because the number is right-justified in the field of 7 characters, the second because the record is padded out to the declared length of 8 characters).
Once a number has been turned into a character-string it can be processed further in the various ways described in section 7. This makes it possible, for example, to write numbers left-justified in a field, ...
Solution 2
This is easier with Fortran 95, but still not trivial. Write the number or other item to a string with a write statement (as in the first answer). Then use the Fortran 95 intrinsic "ADJUSTL" to left adjust the non-blank characters of the string.
Solution 3
And really un-elegant is my method (I program like a cave woman), after writing the simple Fortran write format (which is not LJ), I use a combination of Excel (csv) and ultraedit to remove the spaces effectively getting the desired LJ followed directly by commas (which I need for my specific import format to another software). BF
Solution 4
If what you really want is whitespace between output fields rather than left-justified numbers to leave whitespace you could simply use the X
edit descriptor. For example
format(A20,4X,ES18.8,4X,A12,4X,ES18.8)
will insert 4 spaces between each field and the next. Note that the standard requires 1X
for one space, some of the current compilers accept the non-standard X
too.
Related videos on Youtube
mishaF
Updated on March 13, 2020Comments
-
mishaF over 3 years
I am writing some simple output in fortran, but I want whitespace delimiters. If use the following statement, however:
format(A20,ES18.8,A12,ES18.8)
I get output like this:
p001t0000 3.49141273E+01obsgp_oden 1.00000000E+00
I would prefer this:
p001t0000 3.49141273E+01 obsgp_oden 1.00000000E+00
I tried using negative values for width (like in Python) but no dice. So, is there a way to left-justify the numbers?
Many thanks in advance!
-
mishaF almost 13 yearsI had hoped for something more elegant, but was seeming to settle on a similar solution. Thanks for the answer @ubuntourist
-
jvriesem over 4 yearsThere's a great tutorial of this here: jblevins.org/log/leftjust