Java · Medium · Free
Double comparison — epsilon vs BigDecimal for money?
JavaTrickyFresher
Comparing doubles
double and float use IEEE 754 binary fractions—many decimal values (0.1, money) are not exact. Never use == for business rules; use epsilon tolerance for physics, BigDecimal for money.
| Use case | Approach | Avoid |
|---|---|---|
| Money | BigDecimal with scale + compareTo | double cents |
| Sensor math | epsilon compare | raw == |
| Sorting | Double.compare | subtract and compare to zero |
java
BigDecimal price = new BigDecimal("19.99");
BigDecimal tax = price.multiply(new BigDecimal("0.0825"));
if (price.compareTo(tax) < 0) { /* ... */ }
// Not for money:
double bad = 0.1 + 0.2; // 0.30000000000000004Say "store money as integer minor units or BigDecimal strings, never binary float."