The <code>double</code> Primitive in Java β 64-bit Floating Point
double is Java's default floating-point type: a 64-bit IEEE 754 binary value with ~15 significant decimal digits and range roughly Β±1.8Γ10Β³β°βΈ. Use it for physics, graphics, statistics β not for money.
Declaration
double d = 3.14; // double is the default β no suffix needed
double d2 = 3.14d; // explicit suffix (rarely used)
double e = 1.5e-9; // scientific β 1.5 Γ 10β»βΉ
double nan = Double.NaN; // not-a-number
double inf = Double.POSITIVE_INFINITY;
The 0.1 + 0.2 problem
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1 + 0.2 == 0.3); // false
Binary fractions can't represent decimal 0.1 exactly. Never compare floats with == β compare with a tolerance:
Math.abs(a - b) < 1e-9 // good enough for most cases
NaN and Infinity
0.0 / 0.0 // NaN
1.0 / 0.0 // Infinity
Double.isNaN(result); // can't use == because NaN != NaN !
Double.isFinite(result); // not NaN and not infinite
Use BigDecimal for money
// β Never for currency
double total = 0.1 + 0.2;
// β
BigDecimal total = new BigDecimal("0.10").add(new BigDecimal("0.20")); // 0.30 exactly
Critically: pass BigDecimal a String, not a double. new BigDecimal(0.1) captures the binary noise.
float vs double
Use double by default. float is 32-bit β less precise β and exists mostly for memory-tight graphics or legacy APIs.
Common mistakes
- Using
==to compare. Use a tolerance orDouble.compare. new BigDecimal(0.1)β stores0.1000000000000000055β¦. Always use the String constructor.- Using
doublefor money β round-off accumulates. UseBigDecimalor store integer cents.
Related
Pillar: Java primitives. Siblings: float. Also: arithmetic operators.