Question

In Java 6 there are only two Double#valueOf methods : Double#valueOf(double) and Double#valueOf(String).

1 - Witch method is calling when I execute Double#valueOf(float) ?

According to Javadoc, it seems to be Double#valueOf(String) but Eclipse links with Double#valueOf(double).

2 - Why there is these differents ?

Calling Double.valueOf with float round the result :

System.out.println(Double.valueOf(0.63F));  // displays 0.6299999952316284

Whereas

System.out.println(Double.valueOf(String.valueOf(0.63F)));  // displays 0.63

Extract from javadoc (http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)) :

the float literal 0.1f is equal to the double value 0.10000000149011612

and

string in param is regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic

Was it helpful?

Solution

According to Javadoc, it seems to be Double#valueOf(String) but Eclipse links with Double#valueOf(double).

I couldn't find the place in Javadoc where it would suggest that the String overload would get called in this situation, but Eclipse is right: there is no implicit conversion from float to String, but there is an implicit conversion from float to double, so Double#valueOf(double) is the correct overload.

Calling Double.valueOf with float round the result

It does not "round" the result, it changes its representation to fit double, which has higher precision. However, neither float nor double could represent 0.1 exactly, because it cannot be represented as a sum of negative powers of 2. If you use 0.25 instead of 0.1, this would not happen, because 0.25 is 2 ^ -2, and therefore can be represented precisely in both float and double.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top