19.2: Numeric to Character String Conversion
- Page ID
- 54385
An integer or real value can be converted into a character string using a write operation. The string is provided as the output variable instead of a file unit number. The numeric variable is provided as the input for the write operation.
The following is a simple example that will convert an integer into a string and a real into a string. Some numeric operations are performed on the numeric values and then the resulting strings are concatenated with another string. Concatenation can only be performed on character data types.
! Example program to use an internal write for ! character / numeric conversion. program cvtExample2 implicit none integer :: cvtErr character(50) :: str1, str2, msg1, msg2 integer :: iNum=2468 real :: pi = 3.14, tau write (*,'(a, /)') "Example Conversion Program." ! ---------- ! Convert integer value to a string. iNum = iNum / 100 write (str1, '(i3)', iostat=cvtErr) iNum if (cvtErr == 0 ) then msg1 = "My age is " // str1 write (*,'(a, a)') & "Message 1 = ", msg1 else write (*,'(a, /)') "Error, invalid conversion." end if ! ---------- ! Convert real value to a string. tau = pi * 2.0 write (str2, '(f5.3)', iostat=cvtErr) tau if (cvtErr == 0 ) then msg2 = "The value of TAU is " // str2 write (*,'(a, a, /)') & "Message 2 = ", msg2 else write (*,'(a, /)') "Error, invalid conversion." end if end program cvtExample2
An example of the output for this program is as follows:
Example Conversion Program. Message 1 = My age is 124 Message 2 = The value of TAU is 6.283
Once the numeric values are converted into strings, the character functions and character operations can be used as needed.