If I want to write method converting from float to double.
Is there any case the two would give back different result?
Which version should I use if I don't care about platform consistency?
What if I need it to behave consistently in different platforms?
double f2d(float x) {
return (double) x;
}
or:
strictfp double f2d(float x) {
return (double) x;
}
JLS 5.1.2:
A widening primitive conversion from float to double that is not strictfp may lose information about the overall magnitude of the converted value.
why will this conversion lose info?
strictfp
will make no difference for float
to double
conversion. The reason is in Java Language Specification,
4.2.3. Floating-Point Types, Formats, and Values. In particular:
Note that the constraints in Table 4.2.3-A are designed so that every element of the float value set is necessarily also an element of the float-extended-exponent value set, the double value set, and the double-extended-exponent value set.
Since every element of the float
value set is also an element of the double
value set a float
to double
conversion will be exact regardless of whether it is FP-strict or not.