2

The MS.Internal.DoubleUtil-Class contains the function

public static int DoubleToInt(double val)
{
    return (0 < val) ? (int)(val + 0.5) : (int)(val - 0.5);
}

I wonder why this 'converts' val to an Integer?

HerpDerpington
  • 3,751
  • 4
  • 27
  • 43

3 Answers3

4

The cast from double to int always takes the floor, so adding .5 (or subtracting .5 if it is negative) means 1.6 returns 2, while 1.4 would return 1.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
1

For numbers > 0 it adds 0.5 and truncates. For numbers < 0 it subtracts 0.5 and truncates.

The (int) cast in fact truncates, so (int)7.8 == 7, (int)-7.8 == 7, (int)7.995 == 7 and so on.

So we have:

0-0.499999... is rounded to 0 (0.499999 + 0.5 == 0.999999 trucated == 0)
0.5-1... is rounded to 1 (1 + 0.5 == 1.5 truncated == 1) 

and so on.

The opposite for negative numbers.

Border cases (values outside the int.MinValue - int.MaxValue range) are probably ignored, so are Double special values (NaN, PositiveInfinity, NegativeInfinity)

There could be some problems with some double numbers, because double aren't "precise" (it's complex to explain, try looking for why the double are bad) and often what you see is not what you have, so you could have something you think is 1.5 but in reality is 1.499999999999985 and so it's rounded to 1 instead of 2.

Something like:

double d = 11.3;

// There are 20x += 0.01 
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;
d += 0.01; d += 0.01; d += 0.01; d += 0.01; d += 0.01;

Console.WriteLine("{0}", d);
Console.WriteLine("{0:R}", d);
Console.WriteLine("{0}", DoubleToInt(d));

result:

11.5
11.499999999999996
11
xanatos
  • 109,618
  • 12
  • 197
  • 280
0

This is simply because it casts to (int). The + or - is simply used to round the value.

Belogix
  • 8,129
  • 1
  • 27
  • 32