public static int ToInt32(double d)
{
int id = (int)d;
if (id == d)
{
// This covers -0.0 as well
return id;
}
if (d != d || d == double.PositiveInfinity || d == double.NegativeInfinity)
{
return 0;
}
d = (d >= 0) ? Math.Floor(d) : System.Math.Ceiling(d);
double two32 = 4294967296.0;
d = System.Math.IEEERemainder(d, two32);
// (double)(long)d == d should hold here
long l = (long)d;
// returning (int)d does not work as d can be outside int range
// but the result must always be 32 lower bits of l
return (int)l;
}