Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Medium · Free

Double comparison — epsilon vs BigDecimal for money?

JavaTrickyFresher
Model answer

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 caseApproachAvoid
MoneyBigDecimal with scale + compareTodouble cents
Sensor mathepsilon compareraw ==
SortingDouble.comparesubtract 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.30000000000000004
Say "store money as integer minor units or BigDecimal strings, never binary float."