Course – LS – All

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

>> CHECK OUT THE COURSE

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 example code is available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.