How to pad Fortran floating point output with leading zeros?
This works for me
real :: areal
then
write(*,'(i3.3,f0.6)') int(areal),areal-int(areal)
Zero-padding can be performed for integer fields, so if you printed the result as two separate fields you might be able to make it happen. Here's a way that is less than pretty, but works. Say x
is the value you want to print:
DOUBLE PRECISION x
CHARACTER*6 y
x = 123.4567
WRITE(y,'(F6.4)') x-int(x)
WRITE(*,'(I3.3,A5)') int(x), y(2:5)
y
is declared as a CHARACTER*6
because it needs to hold the fractional part of your number (4 decimal places), a leading zero, and a decimal point. This can be easily changed if you want to show more decimal places, though it would be trickier if you wanted to show a variable number of decimal places.
The I3.3
field descriptor means "print an integer with a maximum field width of 3 and pad left with zeroes so that there are always 3 digits". When printing out the value we take y(2:5)
to strip off the leading zero.
Happy coding!