Trim trailing zeros in Fortran print/write

Viewed 447

How can I print without trailing zeros? For example if there was a function nice:

real*8 ff
ff = -3.5d0
print*, "there are ", nice(ff), " horses"

or a formatter t

print'(a,t,a)', "there are ", ff, " horses"

should give:

there are -3.5 horses
2 Answers

This solution works by limiting the precision (there may be some round off errors after ca 16 decimals) and then checking from the end where the last non-0 character is

function nice(ff) result(out)
    character(:), allocatable :: out
    character(20) :: str
    real*8, intent(in) :: ff
    integer ii
    write(str,'(f20.8)') ff
    str = trim(adjustl(str))
    do ii = len_trim(str),1,-1
        if (str(ii:ii)/="0") exit
    enddo
    out = str(1:ii)
end

Note that interval indexing like (ii:ii) is required for strings.

An alternative and easier approach which will work (so long as the total length is smaller than the character array 'CDUMMY') is shown below:

        PROGRAM MAIN
        IMPLICIT NONE
        REAL*8 FF
        FF = 3.5

! ***** WRITE FF TO A CHARACTER ARRAY. ONCE IN THIS FORM YOU CAN REMOVE TRAILING SPACES
        CHARACTER CDUMMY*12
        WRITE(CDUMMY,'(F12.1)') FF
        WRITE(*,'(3A)')  'There are ',TRIM(ADJUSTL(CDUMMY)),' horses'

        END

If you are not too concerned about spaces (as opposed to trailing zeros), then you could simply write using the format specifier Fx.y. For example, to write a floating point number to one decimal place,set y to 1. x is the total size of the number to be outputted including decimal place. So F6.1 would be okay so long as there are less than '9999.9' horses (I feel sorry for the 10,000th horse). In context, it would like so:

WRITE(*,'(A,F6.1,A)') 'There are ',FF,' horses'

Which would yield the following (the underscores represent spaces):

There are ___3.5 horses

Related