When a double has an ‘exact’ integer value, like so:
double x = 1.0;
double y = 123123;
double z = -4.000000;
Is it guaranteed that it will round properly to 1, 123123, and -4 when cast to an integer type via (int)x, (int)y, (int)z? (And not truncate to 0, 123122 or -5 b/c of floating point weirdness). I ask b/c according to this page (which is about fp’s in lua, a language that only has doubles as its numeric type by default), talks about how integer operations with doubles are exact according to IEEE 754, but I’m not sure if, when calling C-functions with integer type parameters, I need to worry about rounding doubles manually, or it is taken care of when the doubles have exact integer values.
Yes, if the integer value fits in an
int.A
doublecould represent integer values that are out of range for yourinttype. For example,123123.0cannot be converted to anintif yourinttype has only 16 bits.It’s also not guaranteed that a
doublecan represent every value a particular type can represent. IEEE 754 uses something like 52 or 53 bits for the mantissa. If yourlonghas 64 bits, then converting a very largelongtodoubleand back might not give the same value.