Fortran code snippets

I like the f0.d format for printing reals, except that it does not print leading zeros, and for very large numbers the digits after the decimal point may be noise. A program with a subroutine that prints with the f0.6 format but adds leading zeros and switches to scientific notation for large numbers is

module util_mod
implicit none
private
public :: dp, print_real
integer, parameter :: dp = kind(1.0d0)
contains
impure elemental subroutine print_real(x)
! print real x with leading zero for abs(x) < 1
real(kind=dp), intent(in) :: x
if (abs(x) < 1.0_dp) then
   if (x >= 0) then
      print "(F8.6)", x
   else
      print "(F9.6)", x ! space for leading negative sign
   end if
else if (abs(x) > 1.0e22_dp) then ! use scientific notation
   if (x >= 0) then
      print "(ES12.6)", x
   else
      print "(ES13.6)", x ! space for leading negative sign
   end if
else
   print "(F0.6)", x
end if
end subroutine print_real
end module util_mod

program xprint_real
use util_mod, only: dp, print_real
implicit none
call print_real([1.1_dp, 0.9_dp, -0.9_dp, &
   1.0e22_dp, -1.0e22_dp, 1.0e23_dp, -1.0e23_dp])
end program xprint_real

with output

1.100000
0.900000
-0.900000
10000000000000000000000.000000
-10000000000000000000000.000000
1.000000E+23
-1.000000E+23

Fortran has added leading zero format control. How would you use that to print with the f0.6 format but with a leading zero? Do any compilers implement it yet?

2 Likes