PRB: Cast of Float to Long Truncated Value to Be Truncated

ID Number: Q48928

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

SYMPTOMS

In Microsoft C versions 5.1, 6.0, 6.0a, 6.0ax, C/C++ version 7.0, and

in QuickC, versions 2.5 and 2.51, casting a float variable to a long

value can result in a value one less than expected.

CAUSE

This is not a problem with Microsoft C, but is a function of how

floating point numbers are stored in memory. When a float or double

value is converted to an integer number, the value is truncated.

The value 1648 and not 1649 is printed because the float value is

not stored exactly as 1649.0000. The value is stored as

1648.99999...999. When you cast the double value to a long integer,

the number is truncated at the decimal point to 1648.

RESOLUTION

In following code fragment, 1648 is printed instead of 1649.

Sample Code 1

-------------

double i, j;

char r[] = "16.49";

i = atofÒ * 100;

printf ("%ld\n", (long)i);

The workaround for this constraint is to add 0.5 to the double

value before converting to an integer value. The following code

produces the correct result:

Sample Code 2

-------------

/* Compile options needed: none

*/

#include <stdio.h>

#include <math.h>

double i, j;

char r[] = "16.49";

main ()

{

i = atofÒ * 100;

printf ("%ld\n", (long)(i + 0.5));

}

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax 7.00