[There are a few questions on this but none of the answers are particularly definitive and several are out of date with the current C++ standard].
My research shows
Use modf()
which breaks the value into integral and fractional parts. From this direct test, it is known if the double
is a whole number or not. After this, limit tests against the min/max of the target integer type can be done.
#include
bool IsInteger(double x) {
double ipart;
return std::modf(x, &ipart) == 0.0; // Test if fraction is 0.0.
}
Note modf()
differs from the similar named fmod()
.
Of the 3 methods OP posted, the cast to/from an integer may perform a fair amount of work doing the casts and compare. The other 2 are marginally the same. They work, assuming no unexpected rounding mode effects from dividing by 1.0. But do an unnecessary divide.
As to which is fastest likely depends on the mix of double
s used.
OP's first method has a singular advantage: Since the goal is to test if a FP may convert exactly to a some integer, and likely then if the result is true, the conversion needs to then occur, OP's first method has already done the conversion.