This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Casting zero (0) double variable to integer is incorrect

Hi there,

I found very interesting behavior on casting double variables to integer.

The following code gives me strange result:

double dval = 0.;

int ival = (int)dval;   // < ival = 2 - unexpected result

double dval1 = 0.0000001;

int ival2 = (int)dval2; // < ival = 0 - expected

In short words, if the double variable is '0.', then it is casted to integer as 2, does not matter int/long/char. If the variable differs the '0.' to any smallest values, it is casted correctly. Looks very strange for me. Casting from the float variables works as expected.

Environment:

SEGGER Embedded Studio v4.30
Development board PCA10040
Compiler GCC

FPU is enabled (ARM FP ABI Type: hard; ARM FPU Type FPv4-SP-D16)

To handle this I perform casting to float type before, and then to integer type.

What can I do wrong that the cast of the double variables with 0 value to the integer performed incorrectly?

Thank you.

Related