Understanding BigDecimal.equals: How Value and Scale Affect Equality in Java
This article explains why Java's BigDecimal.equals method compares both numeric value and scale, demonstrates common pitfalls with == and equals, shows experimental results for different constructors, and recommends using compareTo for value‑only comparisons to avoid unexpected false outcomes.
BigDecimal is a Java class for high‑precision arithmetic, widely used in finance, e‑commerce, and other domains that require exact decimal calculations.
Many developers mistakenly compare BigDecimal objects with == or assume that BigDecimal.equals() only checks the numeric value, which leads to subtle bugs.
An experiment creates several BigDecimal instances and prints the results of equals() :
BigDecimal bigDecimal = new BigDecimal(1);
BigDecimal bigDecimal1 = new BigDecimal(1);
System.out.println(bigDecimal.equals(bigDecimal1)); // true
BigDecimal bigDecimal2 = new BigDecimal(1);
BigDecimal bigDecimal3 = new BigDecimal(1.0);
System.out.println(bigDecimal2.equals(bigDecimal3)); // true
BigDecimal bigDecimal4 = new BigDecimal("1");
BigDecimal bigDecimal5 = new BigDecimal("1.0");
System.out.println(bigDecimal4.equals(bigDecimal5)); // falseThe output shows true , true , and false , illustrating that equals() can return false when the scales differ.
The Javadoc clarifies that BigDecimal.equals() returns true only if both the value and the scale are identical; therefore 2.0 is not equal to 2.00 under this method.
BigDecimal provides four constructors, each assigning a different scale:
BigDecimal(int)
BigDecimal(long)
BigDecimal(double)
BigDecimal(String)Constructors with int or long set the scale to 0. The double constructor creates a binary approximation, e.g., new BigDecimal(0.1) becomes 0.1000000000000000055511151231257827021181583404541015625 , giving it a large scale. The String constructor preserves the exact decimal representation and its scale, so new BigDecimal("0.1") has a scale of 1.
Because equals() also checks scale, new BigDecimal("1") and new BigDecimal("1.0") are considered unequal, while new BigDecimal(1) and new BigDecimal(1.0) are equal (both have scale 0).
When only the numeric value matters, use compareTo() , which ignores scale and returns 0 for equal values:
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("1.0000");
System.out.println(a.compareTo(b)); // 0In summary, BigDecimal.equals() is strict—it compares both value and scale—so developers should either choose constructors that give the intended scale or prefer compareTo() for value‑only equality checks.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.