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.

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

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

1. Overview

In this tutorial, we’ll talk about the different ways of comparing double values in Java. In particular, it isn’t as easy as comparing other primitive types. As a matter of fact, it’s problematic in many other languages, not only Java.

First, we’ll explain why using the simple == operator is inaccurate and might cause difficult to trace bugs in the runtime. Then, we’ll show how to compare doubles in plain Java and common third-party libraries correctly.

2. Using the == Operator

Inaccuracy with comparisons using the == operator is caused by the way double values are stored in a computer’s memory. We need to remember that there is an infinite number of values that must fit in limited memory space, usually 64 bits. As a result, we can’t have an exact representation of most double values in our computers. They must be rounded to be saved.

Because of the rounding inaccuracy, interesting errors might occur:

double d1 = 0;
for (int i = 1; i <= 8; i++) {
    d1 += 0.1;
 }

double d2 = 0.1 * 8;

System.out.println(d1);
System.out.println(d2);

Both variables, d1 and d2, should equal 0.8. However, when we run the code above, we’ll see the following results:

0.7999999999999999
0.8

In that case, comparing both values with the == operator would produce a wrong result. For this reason, we must use a more complex comparison algorithm.

If we want to have the best precision and control over the rounding mechanism, we can use java.math.BigDecimal class.

3. Comparing Doubles in Plain Java

The recommended algorithm to compare double values in plain Java is a threshold comparison method. In this case, we need to check whether the difference between both numbers is within the specified tolerance, commonly called epsilon:

double epsilon = 0.000001d;

assertThat(Math.abs(d1 - d2) < epsilon).isTrue();

The smaller the epsilon’s value, the greater the comparison accuracy. However, if we specify the tolerance value too small, we’ll get the same false result as in the simple == comparison. In general, epsilon’s value with 5 and 6 decimals is usually a good place to start.

Unfortunately, there is no utility from the standard JDK that we could use to compare double values in the recommended and precise way. Luckily, we don’t need to write it by ourselves. We can use a variety of dedicated methods provided by free and widely known third-party libraries.

4. Using Apache Commons Math

Apache Commons Math is one of the biggest open-source library dedicated to mathematics and statistics components. From the variety of different classes and methods, we’ll focus on org.apache.commons.math3.util.Precision class in particular. It contains 2 helpful equals() methods to compare double values correctly:

double epsilon = 0.000001d;

assertThat(Precision.equals(d1, d2, epsilon)).isTrue();
assertThat(Precision.equals(d1, d2)).isTrue();

The epsilon variable used here has the same meaning as in the previous example. It is an amount of allowed absolute error. However, it’s not the only similarity to the threshold algorithm. In particular, both equals methods use the same approach under the hood.

The two-argument function version is just a shortcut for the equals(d1, d2, 1) method call. In this case, d1 and d2 are considered equal if there are no floating point numbers between them.

5. Using Guava

Google’s Guava is a big set of core Java libraries that extend the standard JDK capabilities. It contains a big number of useful math utils in the com.google.common.math package. To compare double values correctly in Guava, let’s implement the fuzzyEquals() method from the DoubleMath class:

double epsilon = 0.000001d;

assertThat(DoubleMath.fuzzyEquals(d1, d2, epsilon)).isTrue();

The method name is different than in the Apache Commons Math, but it works practically identically under the hood. The only difference is that there is no overloaded method with the epsilon’s default value.

6. Using JUnit

JUnit is one of the most widely used unit testing frameworks for Java. In general, every unit test usually ends with analyzing the difference between expected and actual values. Therefore, the testing framework must have correct and precise comparison algorithms. In fact, JUnit provides a set of comparing methods for common objects, collections, and primitive types, including dedicated methods to check double values equality:

double epsilon = 0.000001d;
assertEquals(d1, d2, epsilon);

As a matter of fact, it works the same as Guava’s and Apache Commons’s methods previously described.

It’s important to point out that there is also a deprecated, two-argument version without the epsilon argument. However, if we want to be sure our results are always correct, we should stick with the three-argument version.

7. Using a Comparator

Another way to compare double values is by using a Comparator. A Comparator is an interface that defines a method for comparing two objects. In this case, we can create a Comparator that compares two double values using the threshold comparison method.

Here is an example of how to create a Comparator for double values:

public class DoubleComparator implements Comparator<Double> {
    private double epsilon;

    public DoubleComparator(double epsilon) {
        this.epsilon = epsilon;
    }

    @Override
    public int compare(Double d1, Double d2) {
        if (Math.abs(d1 - d2) < epsilon) {
            return 0; // equal
        } else if (d1 < d2) {
            return -1; // d1 is less than d2
        } else {
            return 1; // d1 is greater than d2
        }
    }
}

Let’s create a test case to validate our DoubleComparator:

DoubleComparator comparator = new DoubleComparator(0.000001d);
int result = comparator.compare(d1, d2);
assertEquals(0, result);

In this example, we use the compare() method to compare d1 and d2. Since d1 and d2 are close enough (their difference is within the epsilon), the comparator returns 0 to indicate equality.

8. Compare Doubles by Decimal Places

In some cases, we may need to determine whether two double values are equal up to a specified number of decimal places.

We can achieve this by converting both double values to BigDecimal and using the setScale() method to round them to a specific number of decimal places using a rounding mode like RoundingMode.HALF_UP.

Here’s an example that demonstrates this approach:

boolean areEqual(double d1, double d2, int decimalPlaces) {
    BigDecimal bd1 = BigDecimal.valueOf(d1).setScale(decimalPlaces, RoundingMode.HALF_UP);
    BigDecimal bd2 = BigDecimal.valueOf(d2).setScale(decimalPlaces, RoundingMode.HALF_UP);
    return bd1.equals(bd2);
}

We can verify by creating a test case:

double d1 = 0.7999999999999999;
double d2 = 0.8;

assertTrue(areEqual(d1, d2, 1), "Should be equal up to 1 decimal place");
assertTrue(areEqual(d1, d2, 2), "Should be equal up to 2 decimal places");

In this example, the two values d1 and d2 are considered equal up to one and two decimal places because they both round to 0.8 and 0.80, respectively, even though they differ slightly in binary representation.

This approach is handy in financial applications or in any context where formatted numbers are compared for display or reporting purposes.

9. Conclusion

In this article, we’ve explored different ways of comparing double values in Java.

We’ve explained why simple comparison might cause difficult to trace bugs in the runtime. Then, we’ve shown how to compare values in plain Java and common libraries correctly.

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)