Number Parsing in Fortran

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Fortran.

program number_parsing
    use, intrinsic :: iso_fortran_env, only: real64, int64
    implicit none
    
    real(real64) :: f
    integer(int64) :: i, d, u, k
    integer :: stat
    character(len=20) :: error_msg

    ! Parse a float
    read('(F10.3)', '1.234') f
    print *, f

    ! Parse an integer
    read('(I10)', '123') i
    print *, i

    ! Parse a hexadecimal number
    read('(Z10)', '1c8') d
    print *, d

    ! Parse an unsigned integer (Fortran doesn't have unsigned types, so we use int64)
    read('(I10)', '789') u
    print *, u

    ! Parse a basic base-10 integer
    read('(I10)', '135') k
    print *, k

    ! Demonstrate error handling
    read('(I10)', '(A)', iostat=stat, iomsg=error_msg) k
    if (stat /= 0) then
        print *, trim(error_msg)
    end if

end program number_parsing

In Fortran, we use the read statement for parsing numbers from strings. The read statement can be used with internal files (strings) to convert string representations to numeric values.

For floating-point numbers, we use the F edit descriptor. The 10.3 in F10.3 specifies a field width of 10 and 3 decimal places.

For integers, we use the I edit descriptor. The 10 in I10 specifies a field width of 10.

For hexadecimal numbers, we use the Z edit descriptor.

Fortran doesn’t have unsigned integer types, so we use integer(int64) for all integer types.

To handle errors, we use the iostat and iomsg specifiers in the read statement. If an error occurs during parsing, iostat will be non-zero and iomsg will contain an error message.

To run the program, save it as number_parsing.f90 and compile it with a Fortran compiler:

$ gfortran number_parsing.f90 -o number_parsing
$ ./number_parsing
   1.23400000000000     
         123
         456
         789
         135
 Invalid integer

Note that the exact output format may vary depending on the compiler and system settings.

Fortran’s built-in parsing capabilities are more limited compared to some other languages, but they are sufficient for basic number parsing tasks. For more complex parsing needs, you might need to use additional libraries or implement custom parsing routines.