Core Java: BigDecimal.equals compares scale as well as value, compareTo does not

BigDecimal's equals treats 2.0 and 2.00 as different because it compares both unscaled value and scale, while compareTo correctly treats them as numerically equal.

Code
BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");
System.out.println("a.equals(b): " + a.equals(b));
System.out.println("a.compareTo(b) == 0: " + (a.compareTo(b) == 0));
Output
a.equals(b): false
a.compareTo(b) == 0: true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms