Floating-Point Arithmetic and Rounding Errors
What you'll learn: Why floating-point math in Java sometimes produces surprising results, like 0.1 + 0.2 not equaling 0.3.
The Surprising Truth About Decimal Math
You might expect that adding 0.1 + 0.2 would give you exactly 0.3, but in Java (and most programming languages), it doesn't. Try this:
public class Main {
public static void main(String[] args) {
double result = 0.1 + 0.2;
System.out.println(result); // Prints: 0.30000000000000004
}
}
Why does this happen? It's not a bug—it's how computers store decimal numbers.
Binary Representation and Lost Precision
Computers store floating-point numbers in binary (base-2), not decimal (base-10). Just like you can't express 1/3 exactly as a decimal (it's 0.3333... forever), many simple decimals like 0.1 can't be represented exactly in binary.
Think of it like trying to measure something with a ruler that only has inch marks when you need millimeter precision—you'll get close, but not exact.
When Java stores 0.1 as a double, it stores the closest possible binary approximation. When you add two approximations together, tiny errors accumulate, producing results like 0.30000000000000004.
This Affects All Floating-Point Operations
Rounding errors can occur with addition, subtraction, multiplication, and division of float and double values. The errors are usually tiny, but they're always there.
double a = 1.0;
double b = 0.9;
System.out.println(a - b); // Might not be exactly 0.1
Key Takeaway: Floating-point numbers in Java (float and double) are inherently imprecise due to binary representation—never assume exact equality in decimal calculations, and avoid using them for financial data where precision matters.