Floating-Point Best Practices and Pitfalls
What you'll learn: How to avoid common floating-point mistakes and recognize when floats and doubles aren't the right choice.
The Core Problem
By now you know that float and double can't represent all decimal values exactly—they're approximations. This creates traps for unwary programmers, especially in three areas: exact financial calculations, equality comparisons, and accumulating rounding errors.
Common Pitfalls to Avoid
Never Use Floating-Point for Money
If you're calculating prices, interest, or currency, don't use float or double. Rounding errors compound quickly:
double price = 0.1 + 0.2; // You expect 0.3, but get 0.30000000000000004
For money, you'll eventually learn about integer-based approaches (like storing cents as int) or specialized types.
Don't Compare with ==
Remember: comparing floating-point numbers with == is unreliable due to rounding errors. Always use a tolerance-based approach as you learned in "Comparing Floating-Point Numbers Safely."
Watch Out for Accumulation
Repeatedly adding small double values can magnify errors:
double sum = 0.0;
for (int i = 0; i < 1000; i++) {
sum += 0.1; // Errors accumulate with each iteration
}
// sum is NOT exactly 100.0
When Floats and Doubles Are Fine
Use them for:
- Scientific measurements (temperature, distance)
- Graphics and game coordinates
- Statistical approximations
- Any scenario where small inaccuracies don't matter
Key Takeaway: Floating-point types are powerful but imprecise—never use them for exact decimal arithmetic like currency, avoid direct equality checks, and be aware that errors can accumulate in loops or repeated calculations.