eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Correctly handling numbers is crucial to any programming language. However, some applications rely more on the exact values and require a better representation of decimal numbers.

For example, we should avoid number representations that allow rounding errors and overflows while working with money or precise calculations. For such cases, it’s highly recommended to use the BigDecimal class.

Although BigDecimal provides many benefits, it displays a non-intuitive behavior regarding equals() and compareTo() methods. In this tutorial, we’ll dive into their differences, underlying implementations, and implications for these methods.

2. compareTo()

Let’s start with the easiest of these methods: compareTo(). The beauty of it is that its behavior is expected and would be considered consistent and logical for most developers.

This method compares two numbers and returns an integer value that shows if a number is greater, lesser, or equal to another one. In this context, we refer to the equality of two numbers regarding the compareTo() result being zero. Let’s check the following example of the compareTo() logic:

static Stream<Arguments> decimalCompareToProvider() {
    return Stream.of(
      Arguments.of(new BigDecimal("0.1"), new BigDecimal("0.1"), true),
      Arguments.of(new BigDecimal("1.1"), new BigDecimal("1.1"), true),
      Arguments.of(new BigDecimal("1.10"), new BigDecimal("1.1"), true),
      Arguments.of(new BigDecimal("0.100"), new BigDecimal("0.10000"), true),
      Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1000"), true),
      Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1001"), false),
      Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1010"), false),
      Arguments.of(new BigDecimal("0.2"), new BigDecimal("0.19999999"), false),
      Arguments.of(new BigDecimal("1.0"), new BigDecimal("1.1"), false),
      Arguments.of(new BigDecimal("0.01"), new BigDecimal("0.0099999"), false)
    );
}

@ParameterizedTest
@MethodSource("decimalCompareToProvider")
void givenBigDecimals_WhenCompare_ThenGetReasonableResult(BigDecimal fistDecimal,
  BigDecimal secondDecimal, boolean areComparablySame) {
    assertEquals(fistDecimal.compareTo(secondDecimal) == 0, areComparablySame);
}

The compareTo() method treats the numbers 0.1, 0.10, 0.100, and 0.1000 as the same. It ignores trailing zeros, which is quite reasonable and expected in most cases.

3. compareTo() vs. equals()

While it’s highly recommended to respect the consistency between compareTo() and equals(), it isn’t a strict rule. Here’s the snipped from the documentation of the Comparable interface:

It is strongly recommended (though it isn’t required) that natural orderings be consistent with equals.

The BigDecimal class doesn’t follow this recommendation. The discrepancy between the results of these methods might result in unexpected behavior and hard-to-debug issues.

It’s usual for developers to have issues with this method. The documentation refers to BigDecimal and its unusual behavior in the Comparable interface:

One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal numerical values and different representations (such as 4.0 and 4.00). For BigDecimal.equals() to return true, the representation and numerical value of the two BigDecimal objects must be the same.

The BigDecimal documentation also points to the same behavior:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale. Therefore, 2.0 is not equal to 2.00 when compared by this method since the former has [BigInteger, scale] components equal to [20, 1] while the latter has components equal to [200, 2].

However, because this information is in the documentation, we can confidently state that no one reads it. Therefore, let’s discuss the behavior of the equals() method more.

3. equals()

The main quirk of the equals() method is that it considers the scale while comparing two numbers. This means that from its perspective, 1.0 and 1.00 aren’t equal.

In some specific cases, we want to distinguish numbers by their precision; for example, in physics, we tend to treat numbers with different precisions as different.

However, we have additional reasons for such behavior in the BigDecimal class.

3.1. Scale

First of all, the representations of the numbers aren’t the same. The scale is stored in a separate field and defines the floating point’s position:

public class BigDecimal extends Number implements Comparable<java.math.BigDecimal> {
    //...
    private final int scale;
    //...
}

Thus, technically, the numbers with different scales aren’t equal as they have different values in their fields.

3.2. hashCode()

Another exciting aspect is the relationships between the equals() and hashCode(). Considering the numbers that differ only in trailing zeros equal, we should also reflect this in the hashCode() calculation, which would complicate it.

In the current implementation, the scale affects the hash code and is consistent with equals():

@Override
public int hashCode() {
    if (intCompact != INFLATED) {
        long val2 = (intCompact < 0)? -intCompact : intCompact;
        int temp = (int)( ((int)(val2 >>> 32)) * 31  + (val2 & LONG_MASK));
        return 31*((intCompact < 0) ?-temp:temp) + scale;
    } else
        return 31*intVal.hashCode() + scale;
}

The comment for hashCode() explains its behavior:

Two BigDecimal objects that are numerically equal but differ in scale (like 2.0 and 2.00) will generally not have the same hash code.

3.3. Operations

Additionally, the same operations on equal numbers should produce the same results. This might not be true if we work on the number with different scales. Java 17 provides the following example in the documentation:

One example that shows how 2.0 and 2.00 are not substitutable for each other under some arithmetic operations are the two expressions:
new BigDecimal(“2.0” ).divide(BigDecimal.valueOf(3), HALF_UP which evaluates to 0.7 and
new BigDecimal(“2.00”).divide(BigDecimal.valueOf(3), HALF_UP which evaluates to 0.67.

This behavior can be shown better in the example with 4.0 and 4.00:

@ParameterizedTest
@CsvSource({
  "2.0, 2.00",
  "4.0, 4.00"
})
void givenNumbersWithDifferentPrecision_WhenPerformingTheSameOperation_TheResultsAreDifferent(
  String firstNumber, String secondNumber) {
    BigDecimal firstResult = new BigDecimal(firstNumber).divide(BigDecimal.valueOf(3), HALF_UP);
    BigDecimal secondResult = new BigDecimal(secondNumber).divide(BigDecimal.valueOf(3), HALF_UP);
    assertThat(firstResult).isNotEqualTo(secondResult);
}

Dividing 4.0 by three would give 1.3, and dividing 4.00 by three would result in 1.33.

3.4. toString()

As a side note, the toString() representation of the numbers with different precision would produce different results. However, the toString() method isn’t connected to the equals() method, and we should never assume we can use it for comparison.

For example, Sets or other data structures that don’t maintain the order might have different toString() representations despite having the same elements.

While we can understand the reasoning behind such implementation of the equals() method, it’s pretty specific and non-intuitive. This might lead to a problem with assertions, and some Java standard methods and data structures may suffer from it.

4. Additional Things (Bugs) to Consider

Let’s review the implications of this behavior while working with BigDecimal. We should consider the implementation of the equals() method wherever it’s used, explicitly or implicitly.

4.1. distinct()

While working with Stream API, the distinct() method might produce unexpected results as it would compare the numbers based on their equality (meaning the result of the equal method). Let’s check the expected behavior first:

Stream.of("0.0", "0.00", "0.0").map(BigDecimal::new).distinct().toArray()

This code results in the following array:

[ 0.0, 0.00 ]

Let’s sort the stream first before taking the distinct values:

Stream.of("0.0", "0.00", "0.0").map(BigDecimal::new).sorted().distinct().toArray()

Due to the different results from the equals() and compareTo(), we can have different positioning of the elements and distinct assumes that the equal elements are grouped. Thus, we might have an incorrect result:

[ 0.0, 0.00, 0.0 ]

This is a known but non-resolved bug. While it might not be the most common use of the distinct(), without being aware of the implementation, it might result in very subtle bugs in our applications.

4.2. Maps and Sets

The differences in the results for the equals() and compareTo() also affect the HashMaps and HashSets. Let’s take the following BigDecimals values:

static Stream<Arguments> decimalProvider() {
    return Stream.of(Arguments.of(Arrays.asList(
      new BigDecimal("1.1"),
      new BigDecimal("1.10"),
      new BigDecimal("1.100"),
      new BigDecimal("0.10"),
      new BigDecimal("0.100"),
      new BigDecimal("0.1000"),
      new BigDecimal("0.2"),
      new BigDecimal("0.20"),
      new BigDecimal("0.200")),

      Arrays.asList(
        new BigDecimal("1.1"),
        new BigDecimal("0.10"),
        new BigDecimal("0.2"))));
}

The behavior correctly adheres to the outlined logic of the equals method. The result would contain all the numbers from the list because they’re considered to be non-equal:

@ParameterizedTest
@MethodSource("decimalProvider")
void givenListOfDecimals_WhenAddingToHashSet_ThenUsingEquals(List<BigDecimal> decimalList) {
    Set<BigDecimal> decimalSet = new HashSet<>(decimalList);
    assertThat(decimalSet).hasSameElementsAs(decimalList);
}

The additional confusion arises from the fact that sorted Maps and Sets behave differently:

@ParameterizedTest
@MethodSource("decimalProvider")
void givenListOfDecimals_WhenAddingToSortedSet_ThenUsingCompareTo(List<BigDecimal> decimalList,
  List<BigDecimal> expectedDecimalList) {
    Set<BigDecimal> decimalSet = new TreeSet<>(decimalList);
    assertThat(decimalSet).hasSameElementsAs(expectedDecimalList);
}

This happens because they rely on the compareTo() instead of the equals() while checking for the existing elements.

5. Trailing Zeros

The best way to resolve the problem is to create a common representation of a number. Because the main issue arises from the difference in trailing zeros, we can use the stripTrailingZeros() method to resolve it:

@ParameterizedTest
@MethodSource("decimalEqualsProvider")
void givenBigDecimals_WhenCheckEqualityWithoutTrailingZeros_ThenTheSameAsCompareTo(BigDecimal fistDecimal,
  BigDecimal secondDecimal) {
    BigDecimal strippedFirstDecimal = fistDecimal.stripTrailingZeros();
    BigDecimal strippedSecondDecimal = secondDecimal.stripTrailingZeros();
    assertEquals(strippedFirstDecimal.equals(strippedSecondDecimal),
      strippedFirstDecimal.compareTo(strippedSecondDecimal) == 0);
}

While this method requires additional CPU cycles and might affect the performance, it’s a better way to ensure the consistency between the equals() and compareTo().

6. Conclusion

BigDecimal is an important Java class that helps avoid rounding errors and overflow. However, as this article discussed, it might introduce other issues.

We should pay close attention to using BigDecimal instances in data structures that rely on order or equality of elements. The same is true for direct comparison of the numbers.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)