The <code>float</code> Primitive in Java β 32-bit Floating Point
float is a 32-bit IEEE 754 floating-point value β about 7 significant decimal digits, range roughly Β±3.4Γ10Β³βΈ. It's half the memory of a double but also half the precision. Use float only when memory is scarce (large arrays in graphics or audio code). Otherwise stick with double.
The f suffix is mandatory
float pi = 3.14; // β compile error β 3.14 is a double
float pi = 3.14f; // β
f suffix
float pi = (float) 3.14; // β
explicit cast
Precision
float f = 0.1f + 0.2f; // 0.3f β but noisy
double d = 0.1 + 0.2; // 0.30000000000000004
System.out.println(1234567890f); // 1.23456794E9 β precision lost past 7 digits
When to actually pick float
- Very large numeric arrays where 4 bytes/element Γ millions matters (graphics, ML feature tensors).
- APIs that require it (OpenGL, LibGDX, some
java.awtsignatures). - Network or file formats that specify 32-bit floats.
For everything else, double is faster on modern CPUs (no conversion overhead) and avoids a whole class of precision bugs.
NaN and Infinity
Same special values as double: Float.NaN, Float.POSITIVE_INFINITY, Float.isNaN(), Float.isFinite().
Common mistakes
- Forgetting the
fsuffix β "incompatible types: possible lossy conversion from double to float". - Using
floatfor money β worse thandouble. UseBigDecimal. - Mixing
floatanddoubleβ the computation happens indoubleand narrows back. Pick one and stick with it.
Related
Pillar: Java primitives. Sibling: double (almost always the better choice).