0

I have a user-defined integer x which I am casting to a string 'xs' as

integer :: x
read (*,*) x
character xs*4
write (xs, '(I4.4)') x

If x is less than 4 digits in length, i.e. x=25, then xs becomes

0025

I don't want this, and simply want xs='25'. However, I do not know before hand how long x is actually going to be (it is set by the user), just that it will be at most 4 digits. Can I remove the leading zeros? Can I change them to leading whitespace, and then call trim()?

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
pretzlstyle
  • 2,774
  • 5
  • 23
  • 40
  • 2
    Does this answer your question? [How to format an integer to have only the needed size?](https://stackoverflow.com/questions/28728882/how-to-format-an-integer-to-have-only-the-needed-size) – veryreverie May 20 '21 at 15:05
  • The answer found by @veryreverie probably does exactly what you want, if I understand you correctly, but I think it worth noting that an edit descriptor of simply I4 will write the digits padded to length 4 with white space, i.e. no leading zeros. In fact I would say I4.4 is a rather uncommon format descriptor, in my experience I4 is much more commonly be used. – Ian Bush May 20 '21 at 15:19
  • @IanBush, I use `I4.4` when creating data file names for the frames in animations, e.g., `write(name,"(A,I4.4,A)") "frame", i, ".dat"`. Then, at least on Unix-like systems the files are listed in proper order with `animate frame*.dat` – steve May 20 '21 at 15:44
  • @steve agreed it has its uses, just I would suspect i4 is more common – Ian Bush May 20 '21 at 15:47
  • 1
    Although using `I0` would be appropriate, you still get `25 ` (with two trailing blanks) because you're writing to a length-four character variable. Also, as in the question you could use `I4` to get leading whitespace, but instead of `trim` (which again won't do any good because the character variable will still be of the same length, so padded with trailing blanks) you'd want `adjustl`. – francescalus May 20 '21 at 16:06

0 Answers0