Converting Character to Real

Hi all

it’s been pretty easy to convert character to integer or real number without considering the decimals. We can just read the character and it will output integer or real number while ignoring the decimals. Ex:

read (string,*) integernum

read (string,*) realnum

However, I find it very difficult to convert character to real number while considering the decimals (say “2.25” to 2.25). Using read function easily output the 2, but any numbers from 2.00 to 2.99 will result to the same 2 using that function.

Anyone here know how to convert character to real while considering the decimals?
Many thanks

Hi @fallenengineer you can checkout this thread Faster string to double - #80 by hkvzjal there is an ongoing discussion on that topic and how to do it fast

1 Like

What datatype is realnum?

This prints 2.25000000:

program char_to_real
    implicit none
    character(10) :: string
    real :: realnum
    string = "2.25"
    read(string,*) realnum
    print*, realnum
end program char_to_real
2 Likes

This is the key question, the datatype of your target variable is important when calling read(). You can double check by printing your variable, if you print without any format “write(,) realnum” and there are no tailing zeros like “2.0000000” but only “2” it means your variable is actually an integer. otherwise you should get your decimal values

1 Like

Turns out, we shall specify the length of the character. If the len (in your example is 10) is not specified. It will just spills some nonsense numbers.

I myself prefer to have a subroutine to convert character to real number, for example:

> subroutine cn(ch,num)
> !character to real converter
> implicit none
> character(len=5),intent(in)::ch
> real,intent(out)::num
> integer::istat
> 
> read (ch,"(f5.2)",iostat=istat) num
> if (istat/=0) then
>   num=0
> end if
>
> end subroutine

The declaration of real number may be replaced with integer to convert character to integer. In the program we would only need to call the subroutine as:

> call cn(charin,realout)

where charin is the input character type and realout is the output real type.

Above may help other beginners to convert character to real or integer.

Thanks all for your help

1 Like