Formatted output with leading zeros in Fortran

GeneralMike picture GeneralMike · Jan 29, 2013 · Viewed 23.9k times · Source

I have some decimal numbers that I need to write to a text file with leading zeros when appropriate. I've done some research on this, and everything I've seen suggests something like:

  REAL VALUE
  INTEGER IVALUE

  IF (VALUE.LT.0) THEN
    IVALUE = CEILING(VALUE)
  ELSE
    IVALUE = FLOOR(VALUE)
  ENDIF
  WRITE(*,1) IVALUE, ABS(VALUE)-ABS(IVALUE)
1 FORMAT(I3.3,F5.4)

As I understand it, the IF block and ABS parts should allow this to work for all values on -100 < VALUE < 1000. If I set VALUE = 12.3456, the code above should produce "012.3456" as the output, and it does. However if I have something like VALUE = -12.3456, I'm getting "(3 asterisks).3456" as my output. I know the asterisks usually shows up when there are not enough characters provided for in the FORMAT statement, but 3 should be enough in this example (1 character for the "-" and two characters for "12"). I haven't tested this yet with something like VALUE = -9.876, but I'd expect the output to be "-09.8760".

Is there something wrong in my understanding of how this works? Or is there some other limitation of this technique that I'm violating?

UPDATE: Okay I've looked into this some more, and it seems to be a combination of a negative value and the I3.3 format. If VALUE is positive and I have the I3.3, it will put leading zeros as expected. If VALUE is negative and I only have I3 as my format, I get the correct value output, but it will be padded with spaces before the negative sign instead of padded with zeros after the negative (so -9.8765 is output as " -9.8765", but that leading space breaks what I'm using the .txt file for, so it's not acceptable).

Answer

Vladimir F picture Vladimir F · Jan 29, 2013

Tho problem is with your integer data edit descriptor. With I3.3 you require at least 3 digits and the field width is only 3. There is no place for the minus sign. Use I4.3 or, In Fortran 95 and above, I0.3.

Answer to your edit: Use I0.3, it uses the minimum number of characters necessary.

But finally, you just probably want this: WRITE(*,'(f0.3)') VALUE