A sample code using Java double produces surprising results.

UNEXPECTED Result: 0.1d + 0.2d - 0.3d = 5.551115123125783E-17

public class DoubleDemo {
// We see UNEXPECTED Result: 0.1d + 0.2d - 0.3d = 5.551115123125783E-17
private static void demo() {
double problematicRealNumber = 0.1d + 0.2d - 0.3d;
if (problematicRealNumber == 0)
System.out.println("EXPECTED Result: 0.1d + 0.2d - 0.3d =" + 0);
else
System.out.println("UNEXPECTED Result: 0.1d + 0.2d - 0.3d = " + problematicRealNumber);
}
public static void main(String[] args) {
demo();
}
}
view raw DoubleDemo.java hosted with ❤ by GitHub

Same code using Java float does not.

EXPECTED Result: 0.1d + 0.2d - 0.3d = 0

// We see EXPECTED Result: 0.1f + 0.2f - 0.3f = 0
public class FloatDemo {
private static void demo() {
float realNumber = 0.1f + 0.2f - 0.3f;
if (realNumber == 0)
System.out.println("EXPECTED Result: 0.1f + 0.2f - 0.3f = " + 0);
else
System.out.println("UNEXPECTED Result: 0.1f + 0.2f - 0.3f = " + realNumber);
}
public static void main(String[] args) {
demo();
}
}
view raw FloatDemo.java hosted with ❤ by GitHub


Below is the first of a couple of videos to follow on floating point numbers