I want to understand how the Java double type will store its value in memory in Java.
When I run the following code I get unexpected output:
public static void main(String[] args) {
float a = 1.5f;
float b= 0.5f;
double c= 1.5;
double d = 0.5;
float a1 = 1.4f;
float b1= 0.5f;
double c1= 1.4;
double d1 = 0.5;
System.out.println(" a- b is " + (a-b));
System.out.println(" c- d is " + (c-d));
System.out.println("a1-b1 is " + (a1-b1));
System.out.println("c1-d1 is " + (c1-d1));
}
Output:
a- b is 1.0 c- d is 1.0 a1-b1 is 0.9 c1-d1 is 0.8999999999999999
Why is c1-d1 not equal to 0.9?
I also tried other different values but some time it return expected result and some time not.
While you might have heard about rounding errors, you might be wondering why you have a rounding error here.
prints
As you can see, neither
floatnordoublecan represent these values exactly, and when the float or double is printed, some rounding occurs to hide this from you. In this case of float, the rounding to 7 decimal places yields the number you expected. In the case of double which has 16 digits of precision, the rounding error is visible.As @Eric Postpischil, notes whether the
floatordoubleoperation has a rounding error depends entirely on the values used. In this situation, it was the float which appeared to be more accurate even through the represented value was further from 0.9 than the double value.In short: if you are going to use
floatordoubleyou should use a sensible rounding strategy. If you can’t do this, use BigDecimal.prints
When you print a float or double, it assumes that the nearest short decimal value is the one you really want. i.e. within 0.5 ulp.
E.g.
prints