How does Fortran convert a real number to Integer

3.7k Views Asked by At

For example,

SUBROUTINE DoSomething (Z,L)                             
  IMPLICIT DOUBLE PRECISION (A-H,O-Z)                               

  D=Z*77.1234567D0                                           
  L=D                                                      

  RETURN                                                         
 END     

And for talking purposes, let us assume D is equal to -1.5, would in this case L be equals to -1 or -2. In other words, does it round up or round down?

Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

Conversion to an integer type for assignment follows use of the intrinsic function int. The effect is defined as (F2008 13.7.81)

If A is of type real, there are two cases: if|A|<1, INT(A) has the value 0; if |A| ≥1, INT(A) is the integer whose magnitude is the largest integer that does not exceed the magnitude of A and whose sign is the same as the sign of A.

In this case, then, L will take the value -1.

0
On

Either use NINT() which is the nearest integer, or INT(). INT() only returns the signed integer part of a number. NINT() works as follows:

If a is greater than zero, NINT(a) has the value INT(a+ 0.5); if a is less than or equal to zero, NINT(a) has the value INT(a- 0.5).

Specifically NINT(0.5d0) = 1