CINT and Integer Assignments Round x.5 to Nearest Even Integer (42732)






This article was previously published under Q42732

SUMMARY

When a numeric expression ending in .5 is assigned to an integer variable, the binary (b) math version of Macintosh QuickBASIC will round the expression to the nearest even integer. For example, .5 converts to 0, 1.5 converts to 2, 2.5 converts to 2, and 3.5 converts to 4 [in both compiled and interpreted binary (b) math programs].

This rounding to the nearest even integer occurs for the CINT function and for an integer division assigned to an integer variable. This behavior is a feature of the IEEE Floating Point Standard.

In contrast, the Decimal Math version [Microsoft QuickBASIC (d) or Microsoft BASIC (d)] always rounds numbers ending in .5 upward when assigned to integer variables. You can choose the math package that best suits your needs.

MORE INFORMATION

The even rounding of numbers ending in .5 during integer conversion occurs in the following products:
  1. Microsoft QuickBASIC (b) (binary math) Version 1.00 for the Apple Macintosh
  2. Microsoft BASIC Compiler Version 1.00 for the Apple Macintosh (compiled without the "Compile for Decimal Math" option)
  3. Microsoft BASIC (b) (binary math) Interpreter Versions 2.00, 2.10, and 3.00 for the Apple Macintosh
This type of integer rounding complies with the following IEEE standard:

"If the difference between the unrounded operand and the rounded result is exactly one half, the rounded result is even" (Section 5.4 of the "Proposed Standard for Binary Floating-Point Arithmetic")

The purpose of this behavior is to prevent an average upward (or downward) bias as various calculations are rounded. If the number was always rounded up, there would be an upward bias in calculations. Rounding to the nearest even number averages out; therefore, no rounding bias occurs.

The following are two examples of the above rounding behavior:
  1. The following is an example of always rounding expressions ending in .5 to an even number by integer assignment:
       DEFINT A-Z
       INPUT "Type a whole number (1,2,3,4,5,6,...)",INUM
       IRESULT=INUM/2
       PRINT "If INUM/2 ends in .5, it rounds/truncates to even number:"
       PRINT IRESULT
  2. The following is an example of rounding of the CINT() function:
          a=.5
          b=1.0
          c=1.5
          d=2.0
          e=2.5
          cls
          print "CINT (0.5) = "; CINT(A)
          PRINT "CINT (1.0) = "; CINT(B)
          PRINT "CINT (1.5) = "; CINT(C)
          PRINT "CINT (2.0) = "; CINT(D)
          PRINT "CINT (2.5) = "; CINT(E)
    						
OUTPUT FROM:      QuickBASIC (b)  |  QuickBASIC (d)

CINT (0.5) =           0          |         1
CINT (1.0) =           1          |         1
CINT (1.5) =           2          |         2
CINT (2.0) =           2          |         2
CINT (2.5) =           2          |         3

Modification Type: Minor Last Reviewed: 1/8/2003
Keywords: KB42732