Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

The choice between Double vs. BigDecimal in Java can significantly impact performance as well as the precision and accuracy of floating-point numbers. In this tutorial, we’ll compare and contrast the characteristics, advantages, and disadvantages of these two classes, their use cases, and how to address precision and rounding issues with them.

2. Double

The Double class is a wrapper for the double primitive data type, which is well-suited for general-purpose floating-point arithmetic and works well in many scenarios. However, it has some limitations. The most prominent concern is its limited precision. Due to the nature of binary representation, double numbers might suffer from rounding errors when dealing with decimal fractions.

For example, the double literal 0.1 is not exactly equal to the decimal fraction 0.1, but rather to a slightly larger value:

@Test
public void givenDoubleLiteral_whenAssigningToDoubleVariable_thenValueIsNotExactlyEqual() {
    double doubleValue = 0.1;
    double epsilon = 0.0000000000000001;
    assertEquals(0.1, doubleValue, epsilon);
}

3. BigDecimal

The BigDecimal class represents an immutable, arbitrary-precision, signed decimal number. It can handle numbers of any size without loss of precision. Imagine having a powerful magnifying glass that can zoom in on any part of the number line, allowing us to work with large or incredibly tiny numbers.

It consists of two parts: an unscaled value (an integer with arbitrary precision), and the scale (which indicates the number of digits after the decimal point). For example, the BigDecimal 3.14 has an unscaled value of 314 and a scale of 2.

The BigDecimal class offers better precision than Double, as it can perform calculations with arbitrary-precision decimals, avoiding the rounding errors arising from Double’s binary representation. That’s because BigDecimal uses integer arithmetic internally, which is more accurate than floating-point arithmetic.

Let’s see some examples of how to use the BigDecimal class in Java:

private BigDecimal bigDecimal1 = new BigDecimal("124567890.0987654321");
private BigDecimal bigDecimal2 = new BigDecimal("987654321.123456789");

@Test
public void givenTwoBigDecimals_whenAdd_thenCorrect() {
    BigDecimal expected = new BigDecimal("1112222211.2222222211");
    BigDecimal actual = bigDecimal1.add(bigDecimal2);
    assertEquals(expected, actual);
}

@Test
public void givenTwoBigDecimals_whenMultiply_thenCorrect() {
    BigDecimal expected = new BigDecimal("123030014929277547.5030955772112635269");
    BigDecimal actual = bigDecimal1.multiply(bigDecimal2);
    assertEquals(expected, actual);
}

@Test
public void givenTwoBigDecimals_whenSubtract_thenCorrect() {
    BigDecimal expected = new BigDecimal("-863086431.0246913569");
    BigDecimal actual = bigDecimal1.subtract(bigDecimal2);
    assertEquals(expected, actual);
}

@Test
public void givenTwoBigDecimals_whenDivide_thenCorrect() {
    BigDecimal expected = new BigDecimal("0.13");
    BigDecimal actual = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);
    assertEquals(expected, actual);
}

4. Comparisons and Use Cases

4.1. Comparison Between Double and BigDecimal

Converting from Double to BigDecimal is relatively straightforward. The BigDecimal class provides constructors that accept a double value as a parameter. However, the conversion doesn’t eliminate the precision limitations of a Double. Conversely, converting from BigDecimal to Double can result in data loss and rounding errors when fitting into Double’s constrained scope.

Let’s see both scenarios, that is, converting properly and losing precision:

@Test
void whenConvertingDoubleToBigDecimal_thenConversionIsCorrect() {
    double doubleValue = 123.456;
    BigDecimal bigDecimalValue = BigDecimal.valueOf(doubleValue);
    BigDecimal expected = new BigDecimal("123.456").setScale(3, RoundingMode.HALF_UP);
    assertEquals(expected, bigDecimalValue.setScale(3, RoundingMode.HALF_UP));
}
@Test
void givenDecimalPlacesGreaterThan15_whenConvertingBigDecimalToDouble_thenPrecisionIsLost() {
    BigDecimal bigDecimalValue = new BigDecimal("789.1234567890123456");
    double doubleValue = bigDecimalValue.doubleValue();
    BigDecimal convertedBackToBigDecimal = BigDecimal.valueOf(doubleValue);
    assertNotEquals(bigDecimalValue, convertedBackToBigDecimal);
}

In terms of speed and range, the utilization of hardware-level floating-point arithmetic in Java’s Double makes it faster than BigDecimal. The Double class covers a broad spectrum, accommodating both large and small numbers. However, its confinement within a 64-bit structure introduces precision limitations, especially for extremely large or small numbers. In contrast, BigDecimal presents a more extensive range of values and better precision across a wide array of values.

There are also differences in memory usage. Java’s Double is more compact, which results in more efficient memory usage. On the other hand, BigDecimal’s strength in arbitrary-precision arithmetic entails higher memory consumption. This can have implications for our application performance and scalability, especially in memory-intensive contexts.

4.2. Use Cases

Double effortlessly interfaces with other numeric types, making it a convenient choice for basic arithmetic. It’s the go-to option when performance is a priority. Double’s speed and memory efficiency make it a solid choice for applications such as graphics and game development, which often involve real-time rendering and complex visual effects. Here, performance is crucial to maintain smooth user experiences.

On the other hand, BigDecimal shines when dealing with monetary calculations, where precision errors can result in substantial financial losses. It’s also a savior in scientific simulations requiring absolute precision. While BigDecimal may be slower and more memory-intensive, the assurance it provides in terms of accuracy can be invaluable in critical scenarios.

As a result, BigDecimal is better suited for tasks in financial applications, scientific simulations, engineering and physical simulations, data analysis and reporting, and other domains where precision is critical.

4.3. Precision and Rounding Considerations

With BigDecimal, we get to decide how many decimal places our calculations will have. This is useful when we need exact decimal calculations as it can store each decimal digit as-is.

We can also choose how rounding happens in our calculations. Different rounding modes have different effects on our results, such as:

  • UP: increases the number to the next higher value (when we want to ensure that a value is never less than a certain amount)
  • DOWN: decreases the number to the preceding lower value (when we want to ensure that a value is never greater than a certain amount)
  • HALF_UP: rounds up if the discarded fraction is greater than 0.5
  • HALF_DOWN: rounds down if the discarded fraction is less than 0.5

This level of control over rounding and precision is another reason why BigDecimal is better for financial calculations when we need things to be accurate and uniform.

Double introduces chances of tiny errors creeping in because of how computers represent numbers. Representing repeating decimals, like 1/3, can get tricky as they’ll result in an infinite binary expansion.

Simple numbers like 0.1 can get similarly messy when we try to represent them in binary (base 2). We’d get a repeating fraction like 0.00011001100110011… Computers have a limited number of bits to represent these fractions, so they have to round them off at some point. As a result, the stored value isn’t exactly 0.1, and this can lead to tiny errors when we perform calculations.

4.4. Comparison Table

Let’s summarize what we’ve learned about Double vs. BigDecimal in a table:

Aspect Double BigDecimal
Precision Limited Arbitrary
Range Broad (both large and small) Extensive
Memory Usage Compact Higher
Performance Faster Slower
Use Cases General purpose Financial, Scientific

5. Conclusion

In this article, we’ve discussed the nuances between the Java Double and BigDecimal types and the trade-offs between precision and performance when using them.

As usual, the code samples are 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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.