How about this:
double d = ...;
if ((double)(float)d == d) {
System.out.println(d + " fits into float!");
}
The idea is pretty simple: We first cast to float
and then back to double
and check whether the result is still the same. If d
does not fit into float, then some precision would have been lost at the (float)d
cast and thus the result would be different.
Strictly speaking, the cast back to double
is not necessary as the comparision operator will do this cast implicitly, so (float)d == d
is also fine.
If you are worried about the performance of this, because many float operations are a lot slower than comparable int operations: This is pretty much a non-issue here. Conversion between float and double is extremely efficient in modern CPUs. It can even be vectorized! There are the cvtpd2ps
and cvtps2pd
instructions in the SSE2
instruction set that perform the conversion from double to float and vice versa (4 values are converted at once). The instructions have a latency of 4 cycles on all Intel CPUs that support them. 4 cycles for 4 conversions is extremely fast.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…