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

In this tutorial, we’ll look at a range of options in Java for truncating a double to two decimal places. We’ll see methods that leave us with a String and options for returning Numbers as well.

2. Using Math.floor() and Math.ceil() Rounding

The first method we’ll examine is using the Math class to remove extra decimal places. To truncate a positive number to two decimal places, we first multiply our double by 100, moving all the numbers we want to keep in front of the decimal place. Next, we use Math.floor() to round down, removing everything after the decimal place. Finally, we divide by 100 to undo the previous multiplication:

@Test
void givenADouble_whenUsingMath_truncateToTwoDecimalPlaces(){
    double positive = 1.55555555;
    double truncated = Math.floor(positive * 100) / 100;
    assertEquals("1.55", String.valueOf(truncated));

    double negative = -1.55555555;
    double negativeTruncated = Math.ceil(negative * 100) / 100;
    assertEquals("-1.55", String.valueOf(negativeTruncated));
}

The process is almost identical for a negative number, but instead of Math.floor(), we use Math.ceil() to round up. We could’ve added extra code to detect if the double is negative or positive and automatically use the correct method if we wanted.

For removing more or less decimal places, we’d add or remove zeros to the number we multiplied and divided by. For example, to keep three decimal places, we’d multiply and divide by 1000. This method is useful if we need to keep our double as a double and not end up converting it to a String.

3. Using String.format()

Let’s move on to options that are designed for display purposes rather than calculations. We’ll get a String back from these methods but can always convert the result back to a double if needed. The String.format() method takes two arguments. Firstly, the format we want to apply, and secondly, the arguments referenced by the format. To truncate to two decimal places, we’ll use the format String “%.2f”:

@Test
void givenADouble_whenUsingStringFormat_truncateToTwoDecimalPlaces() {
    double positive = 1.55555555;
    String truncated = String.format("%.2f", positive);
    assertEquals("1.56", truncated);

    double negative = -1.55555555;
    String negativeTruncated = String.format("%.2f", negative);
    assertEquals("-1.56", negativeTruncated);
}

 

The ‘f’ at the end of our format String instructs the formatter to produce a decimal format, and the ‘.2’ means we want two digits after the decimal place. We could adjust this to truncate to the amount of decimal places required. We can see in the test that the result has, in fact, rounded up rather than truncating, so depending on our requirements, this may not be suitable.

4. Creating a String Using NumberFormat

NumberFormat is an abstract class designed to let us format any number. Because it’s an abstract class, we need to use getNumberInstance() first to receive an object we can use. Note that this will use our default locale unless we instruct it to do otherwise. We can follow that by using setMaximumFractionDigits() to say how many decimal places we want. Finally, because we want to truncate rather than round, we call setRoundingMode() with the argument RoundingMode.DOWN:

@Test
public void givenADouble_whenUsingNumberFormat_truncateToTwoDecimalPlaces(){
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode(RoundingMode.DOWN);

    double value = 1.55555555;
    String truncated = nf.format(value);
    assertEquals("1.55", truncated);

    double negativeValue = -1.55555555;
    String negativeTruncated = nf.format(negativeValue);
    assertEquals("-1.55", negativeTruncated);
}

With our NumberFormat setup, it’s then as easy as calling format() with our double. In our test above, we can see that it performs equally well with positive and negative numbers.

5. Creating a String Using DecimalFormat

DecimalFormat is a subclass of NumberFormat specifically designed for decimals. It’s a concrete class, so we can go ahead and make an instance of it directly, passing in our desired pattern to the constructor. We’ll pass in “#.##.” here, the number of hashes after the decimal places indicates how many to keep:

@Test
public void givenADouble_whenUsingDecimalFormat_truncateToTwoDecimalPlaces(){
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.DOWN);

    double value = 1.55555555;
    String truncated = df.format(value);
    assertEquals("1.55", truncated);

    double negativeValue = -1.55555555;
    String negativeTruncated = df.format(negativeValue);
    assertEquals("-1.55", negativeTruncated);
}

Like with NumberFormat earlier, we’ve specified the use of RoundingMode.DOWN. We see again that this solution handles positive and negative numbers well, making it useful.

6. Optimum Accuracy With BigDecimal

Java’s BigDecimal class is best suited to dealing with truncating decimal places directly while keeping the result as a number we can work with. If it’s possible to use this instead of a double, it may be the best option. We can create a BigInteger by passing our double value into the constructor and directly telling it to keep two decimal places by rounding down at the same time:

@Test
void givenADouble_whenUsingBigDecimal_truncateToTwoDecimalPlaces(){
    BigDecimal positive = new BigDecimal(2.555555).setScale(2, RoundingMode.DOWN);
    BigDecimal negative = new BigDecimal(-2.555555).setScale(2, RoundingMode.DOWN);
    assertEquals("2.55", positive.toString());
    assertEquals("-2.55", negative.toString());
}

We’ve cast the results to Strings for the purposes of this test to make it visually clear what the result is. However, we could have gone on to perform further calculations using the truncated outputs if we wanted to.

7. Conclusion

We’ve looked at five different ways we can truncate a double in Java. We’ve seen that String.format(), NumberFormat, and DecimalFormat are usable if we’re creating something for display purposes as they output Strings. Of course, we can always use Double.parseDouble() to convert our Strings back to doubles. Alternatively, we can either use the Math class or BigDecimal to keep our truncated values as numbers for further calculations.

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)