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

The most natural choice for us to deal with numbers in Java is to use the various primitive types available. We can use float or double to represent fractional numbers.

This can be sufficient in certain use cases, but in others, especially when accuracy and precision are a requirement, BigDecimal is a better choice. Sometimes, we might need to convert from a float value to a BigDecimal. We’ll explore various ways to do it in this article.

2. Brief Description of float and BigDecimal Types

Before discussing converting from float to BigDecimal, let’s describe them briefly.

2.1. float

The primitive float is a 32-bit type used to represent floating point numbers, i.e., fractional numbers. The float implementation follows the IEEE 754 specification, a widespread standard. It has its Java class counterpart named Float. We also have a 64-bit version named double. We can call a float a single-precision type and double a double-precision type.

The internal implementation of floating point numbers in computers is inherently not accurate. Representing real numbers with exact precision would require infinite bits. We can easily see what problems can arise by running some simple tests:

@Test
public void whenFloatComparedWithDifferentValues_thenCouldMatch() {
    assertNotEquals(1.1f, 1.09f);
    assertEquals(1.1f, 1.09999999f);
}

So, even though “1.1” and “1.09999999” are different numbers, they look the same when compared to each other in a Java program using float types.

We can see what the internal representation of various float numbers is by using the online tool FloatConverter and testing it with the fraction “1.1” used in the above example. The internal value stored by the computer, according to the tool, is “1.10000002384185791015625”.

When we convert a fractional number from decimal to binary, we need a specific number of bits, which could be infinite for some fractions. In the computer, we have a limited number of bits available. If we convert back this finite representation to the decimal base again, we can get a result different from the original one.

We’ll see various conversion approaches from float to BigDecimal in the following sections, using the 1.10000002384185791015625f value as a consistent float example to convert to ease the discussion since we know it is accurately represented in IEEE 754 binary form.

2.2. BigDecimal

The BigDecimal class is the recommended way to deal with fractional numbers when we require more accuracy and precision. For instance, this is often the case with financial applications.

It has a so-called “unscaled” part, which is an integer with arbitrary precision (limited only by available memory), and a 32-bit integer part, named “scale”, representing the number of digits to the right of the decimal point.

BigDecimal provides methods to perform various operations on numbers and format conversions. A BigDecimal instance represents a single fractional number. We can use the toString method to obtain a String representation of an instance.

3. How To Convert a float to BigDecimal

BigDecimal has a number of constructors and methods to perform type conversions, including float to BigDecimal. We need to take care though, because of the limits of the floating point number representation implemented by the Java float type. We’ll see different ways of performing the conversion in the following sections.

3.1. Using BigDecimal double Constructor with float Argument

One of the constructors of BigDecimal takes a double as a parameter. We can write a simple test to evaluate the result of the conversion when passing to it a float argument:

@Test
public void whenCreatedFromFloat_thenMatchesInternallyStoredValue() {
    float floatToConvert = 1.10000002384185791015625f;
    BigDecimal bdFromFloat = new BigDecimal(floatToConvert);
    assertEquals("1.10000002384185791015625", bdFromFloat.toString());
}

We have used 1.10000002384185791015625f, which is the same value we encountered using the online tool, and we know it is accurately represented. We can see here that BigDecimal performs a conversion consistent with the IEEE 754 representation.

With the BigDecimal float constructor, in real scenarios with existing float values, we can at least be confident that the conversion is aligned with the internal floating-point representation. It’s up to the programmer to deal with the BigDecimal resulting values with caution.

3.2. Using BigDecimal Constructor with String Argument

The most reliable way to initialize a BigDecimal with a fractional number is to use its constructor with a String parameter, passing an input value originally represented as a String object. Typical scenarios are those in which input numbers come from a user interface and are stored as String objects. Those numbers can be preserved in their original representation by using the constructor mentioned above:

@Test
public void whenCreatedFromString_thenPreservesTheOriginal() {
    BigDecimal bdFromString = new BigDecimal("1.1");
    assertEquals("1.1", bdFromString.toString());
}

In this article, though, we are covering float to BigDecimal conversion. We take a float value, use the toString method of the Float class to generate the String representation, and then pass it to the BigDecimal constructor:

@Test
public void whenCreatedFromFloatConvertedToString_thenFloatInternalValueGetsTruncated() {
    String floatValue = Float.toString(1.10000002384185791015625f);
    BigDecimal bdFromString = new BigDecimal(floatValue);
    assertEquals("1.1", floatValue);
    assertEquals("1.1", bdFromString.toString());
}

In the above test, we can see that the Float toString method gives “1.1” when applied to 1.10000002384185791015625f, and the BigDecimal String constructor just preserves this intermediate String value.

Converting existing float values to BigDecimal by its String constructor is not reliable in terms of preserving the precision of their internal representation.

3.3. Using BigDecimal valueOf  Method

Besides its constructors, BigDecimal also has a valueOf static method to perform the conversion, with a double as the only argument. We can see from the BigDecimal source code that its implementation simply passes the result of the Double toString method to the String constructor :

public static BigDecimal valueOf(double val) {
    return new BigDecimal(Double.toString(val));
}

The Double toString execution has the effect of truncating 1.10000002384185791015625f to “1.100000023841858”:

@Test
public void whenDoubleConvertsFloatToString_thenFloatValueGetsTruncated() {
    assertEquals("1.100000023841858", Double.toString(1.10000002384185791015625f));
}

Since the valueOf implementation is just Double.toString(value), we expect the same result by executing it:

@Test
public void whenCreatedByValueOf_thenFloatValueGetsTruncated() {
    assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f).toString());
}

We can conclude that the use of the valueOf method retains less precision than the constructor with a float argument.

4. Conclusion

In this article, we have described several ways of converting float values to BigDecimal. The BigDecimal constructor with a float argument has the best result in keeping the precision of an existing float value.

We can also conclude that if we want complete control of the initialization of BigDecimal with fractional numbers, we should provide values originally represented as String objects to the String constructor.

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)