Two "correct" ways to test:
- Isolate the fraction with
std::fmod(x, 1.0)
.
- Discard the fraction using
floor
or ceil
or trunc
, e.g. test whether x == std::floor(x)
.
And one incorrect way:
- Casting to an integral type will fail (with undefined behavior!) for numbers outside the range of the destination type, so this is not suitable for validation of untrusted input (and if the input is trusted, why does it need to be validated?)
A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.