// FloatRoundErr.java: shows that float does not represent the value exactly. class FloatRoundErr { public static void main(String[] arg) { // ******************************************* // Demo computation in float representation // ******************************************* float f1, f2; f1 = 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f + 0.2f; f2 = 2.0f; System.out.println ("Float test result:"); System.out.println ("=================="); System.out.println ("f1 = " + f1); System.out.println ("f2 = " + f2); // Bad idea to test floating value for equality if (f1 == f2) { System.out.println ("f1 == f2"); } else { System.out.println ("f1 != f2"); } // This is the way to test if float value are more or less equal... if (Math.abs(f1-f2) < 0.0001) { System.out.println ("f1 is approximately equal to f2"); } else { System.out.println ("f1 is very different from f2"); } } }