简体   繁体   中英

How java stores float v double

I realize a decimal number can only be so precise stored as a float in a binary system but what I don't understand is what is happening at the 7 decimal place in my output of 10/7.

In my first output test I noticed that the 5 (7th place) at the end of the float v the 4 (7th place) followed by a 2 in the double. I would think the 7th place in the float would be a 4 since the 8th place in the double is a 2.

Float 1.4285715 Double 1.4285714285714286

I then ran the next output test using the float format to 17 places. The 8th place in each is different - the float is a 6 which is why the 7th place is rounded to 5 I assume.

Float 1.428571462631225600 Double 1.428571428571428600

In the third output test I tried a direct cast with the string format to see what would happen. I got the same results as the second test.

If I have a simplistic question to a complex floating point storage method - I do apologize.

    float f = 10/7f;
    double d = 10/7d;

    System.out.format
        ("Float  %1s\nDouble %2s\n", f,d);
    /*
     *  Float  1.4285715
        Double 1.4285714285714286
     */

    System.out.format
        ("Float  %1$.17f\nDouble %2$.17f\n", f,d);
    /*
     *  Float  1.428571462631225600
        Double 1.428571428571428600
     */

    System.out.format
        ("Float  %1s\nDouble %2s\n", (double)f,d);
    /*
     *  Float  1.4285714626312256
        Double 1.4285714285714286
     */

In my first output test I noticed that the 5 (7th place) at the end of the float v the 4 (7th place) followed by a 2 in the double. I would think the 7th place in the float would be a 4 since the 8th place in the double is a 2.

This expectation only makes sense if you think that floats are stored internally in decimal and rounded to some number of decimal digits. But this is not true, floats are stored internally in binary and rounded to some number of binary digits.

Your expectations are based on a misunderstanding of how floating point numbers are stored. You see doubles having more accurate decimal places only because this is consequence of them having more accurate binary places. The implementation does not store the numbers in a decimal form at all.

For a simplified explanation try this site:

http://floating-point-gui.de/basic/

For a very detailed explanation try this:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

It appears that when you use a float it uses a default precision of 8 digits for this number. When you specify a precision it makes it clear it actually uses double to calculate the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM