Java Floating Point Comparison Gotcha

🚨 This small Java mistake can give wrong comparisons I used to write this: if (price == 0.1 + 0.2) { // logic } Looks correct… but it may fail ❌ --- 👉 Why? Floating-point calculations are not always exact in Java. 👉 0.1 + 0.2 = 0.30000000000000004 So comparison with "==" can fail. --- ✅ Better way: if (Math.abs(price - (0.1 + 0.2)) < 0.0001) { // logic } --- 💡 Lesson: Never use "==" for floating-point comparison. Small detail… but critical in real applications. Have you faced this before? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning

To view or add a comment, sign in

Explore content categories