1

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

4

1 回答 1

3

根据 Javadoc,它似乎是Double#valueOf(String)Eclipse 与Double#valueOf(double).

我在 Javadoc 中找不到建议String在这种情况下调用重载的地方,但 Eclipse 是正确的:没有从 to 的隐式转换floatString但是有从floatto的隐式转换double,所以Double#valueOf(double)是正确的重载.

使用浮点数调用 Double.valueOf 结果

它不会“四舍五入”结果,而是将其表示更改为 fit double,具有更高的精度。但是,两者都float不能准确double表示0.1,因为它不能表示为 的负幂之和2。如果您使用0.25而不是0.1,则不会发生这种情况,因为0.25is 2 ^ -2,因此可以在floatand中精确表示double

于 2013-06-12T15:40:49.843 回答