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.
Java uses IEEE-754 for representing floating point numbers. You can read more about the IEEE-754 standard in many places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With