program testIntToString print *,('"',inttostring(i),'",',i=-100,100) contains function IntToString(i) ! This version can be used in I/O statements implicit none integer :: i ! The following elaborate declaration is required to define a string ! having just enough positions to hold all the digits of the integer, ! and the sign character. ! It contains constants no greater than 10000, so as to be acceptable ! on machines having a default integer kind of 16 bits or more. ! (borrowed from "Algorithms and Data Structures in F and Fortran" ! By Robin A. Vowels - Published by Unicomp, 1998. ISBN 0-9640135-4-1) ! character (len = 1 + & ! For 1-digit ! min (abs(i/10), 1) + & ! For 2-digit->1 ! min (abs(i/100), 1) + & ! For 3-digit->1 ! min (abs(i/1000), 1) + & ! For 4-digit->1 ! min (abs(i/10000), 1) + & ! For 5-digit->1 ! min (abs(i/10000)/10, 1) + & ! For 6-digit->1 ! min (abs(i/10000)/100, 1) + & ! For 7-digit->1 ! min (abs(i/10000)/1000, 1) + & ! For 8-digit->1 ! min (abs(i/10000)/10000, 1) + & ! For 9-digit->1 ! min (abs(i/10000)/10000/10, 1) + & ! For 10 digits ! min (abs(i/10000)/10000/100, 1) + & ! For 11 digits ! min (abs(i/10000)/10000/1000, 1) + & ! For 12 digits ! min (abs(i/10000)/10000/10000, 1) + & ! For 13 digits ! min (abs(i/10000)/10000/10000/10, 1) + & ! For 14 digits ! min (abs(i/10000)/10000/10000/100, 1) + & ! For 15 digits ! min (abs(i/10000)/10000/10000/1000, 1) + & ! For 16 digits ! min (abs(i/10000)/10000/10000/10000, 1) + & ! For 17 digits ! min (abs(i/10000)/10000/10000/10000/10, 1) + & ! For 18 digits ! min (abs(i/10000)/10000/10000/10000/100,1) - & ! For 19 digits ! min (max(i, -1), 0) & ! For -ive nums ! ) :: IntToString character( max(1, int(log10(real(abs(i))+0.1)) + (3-sign(1,i))/2) )& :: IntToString integer :: val , p , izero=iachar('0') if ( i<0 ) then IntToString(1:1) = '-' elseif ( i==0 ) then IntToString(1:1) = '0' endif val = abs(i) p = len(IntToString) do while( val>0 ) IntToString(p:p) = achar(izero + mod(val,10)) val = val/10 p = p - 1 end do end function IntToString end program testIntToString