0
    float f = 8.69f;
    int a = Float.floatToIntBits(f);
    String floatStr = Integer.toBinaryString(a);

    double d1 = f;
    long b = Double.doubleToLongBits(d1);
    String convertStr = Long.toBinaryString(b);

    double d2 = 8.69;
    long c = Double.doubleToLongBits(d2);
    String doubleStr = Long.toBinaryString(c);

    System.out.println(floatStr);
    System.out.println(convertStr);
    System.out.println(doubleStr);

the output is :

1000001000010110000101000111101 100000000100001011000010100011110100000000000000000000000000000 100000000100001011000010100011110101110000101000111101011100001

When convert float to double, why the jvm only copy bits from float, then adding zeros to the rest bits of the double, rather than calculate the real bits like the third line in output.

Kun Yan
  • 9
  • 1
  • Because thats not possible. You can't calculate more precision which was already lost. – tkausl Jun 23 '16 at 08:40
  • Do you assume `8.69d` and `8.69f` are the same number ? They're not, the lost precision can't be restored at conversion because the float value has no link to the literal you used. – Denys Séguret Jun 23 '16 at 08:42
  • Avoid using floats. Just use double. Memory space shouldn't really be an issue unless you are an astronomer... – vikingsteve Jun 23 '16 at 08:43
  • @vikingsteve There are many cases when you deal with many many numbers, not just in astronomy. Imagine thousands of sensors in a plant, each one outputting a few measures every milliseconde... and you do decennial analysis. – Denys Séguret Jun 23 '16 at 08:44

0 Answers0