private static void floatAddition() {
float a = 0.1f;
float b = 0.2f;
System.out.println(a+b);
}
// output = 0.3Why does it print
0.3?It prints
0.3because of how Java formatsfloatvalues for output, combined withfloathaving fewer digits of precision thandouble.
Even though it looks clean on your screen, the underlying binary value is still imprecise.
The Two Reasons Behind This Behavior
1. The Print Formatter (Float.toString()) Hides the Error
When you call System.out.println() on a float, Java uses an algorithm (Float.toString()) that rounds and shortens the number to the shortest decimal representation that can accurately distinguish it at single-precision (7 digits). Because the error falls outside those 7 digits, the printer rounds it off and displays "0.3".
2. How to See the Real Inaccuracy
If you cast that same sum to a double or print it with more decimal places, the underlying binary error will immediately show up:
public class FloatTest {
public static void main(String[] args) {
float a = 0.1f;
float b = 0.2f;
System.out.println("Normal print: " + (a + b));
// Output: 0.3
// Cast to double to see the hidden bits:
System.out.println("Casted to double: " + (double)(a + b));
// Output: 0.30000001192092895
}
}Where does 0.30000001192092896 come from?
When you ran float a = 0.1f; float b = 0.2f; System.out.println(a + b);, Java performed arithmetic using 32-bit single-precision floating-point numbers defined by the IEEE 754 standard.
1. The 32-Bit Floating-Point Breakdown
A 32-bit float has:
- 1 Sign bit (
for positive) - 8 Exponent bits (using a bias of
) - 23 Mantissa (fraction) bits
Because
- Stored value of
0.1fin binary: - Stored value of
0.2fin binary:
2. Adding Them Together
When the CPU adds these two imperfect binary numbers together in single precision:
The closest 32-bit IEEE 754 float that represents this sum is encoded with the exact bits:
- Sign:
0 - Exponent:
01111101(representing) - Mantissa:
00110011001100110011010
3. Why does it print 0.30000001192092896?
When you pass that raw 32-bit float into System.out.println(), Java converts it to a 64-bit double to format it as text. Converting that specific 32-bit float bit pattern into its decimal equivalent yields:
Summary
The number
0.30000001192092896is the exact decimal value of the 32-bit binary float that closest approximates the mathematical sum of0.1f + 0.2f. It is the computer revealing its internal binary rounding error.