SoFunction
Updated on 2025-04-28

Summary of BigDecimal usage problem in Java

This article lets me explain in detail the BigDecimal class in Java, including its purpose, applicable scenarios, and potential problems.

1. What is BigDecimal?

BigDecimalIs a class in Java used to represent decimal numbers of arbitrary precision. It solvesfloatanddoubleThe problem of accuracy loss that may occur when performing accurate calculations.BigDecimalThe class provides methods to add, subtract, multiply, divide numbers, and other operations, and can control the rounding mode.

2. Why do you need BigDecimal?

floatanddoubleTypes are binary-based floating point representations that cannot accurately represent certain decimal numbers (e.g. 0.1). This will lead to errors in conducting scenarios involving currency, finance, and other scenarios that require precise calculations.

For example:

double a = 0.1;
double b = 0.2;
double sum = a + b;
(sum); // Output:0.30000000000000004 😱

You can see,0.1 + 0.2The result is not accurate0.3. andBigDecimalThis problem can be avoided. ✅

3. BigDecimal usage scenarios

  • Financial computing:Currency calculation, interest rate calculation, tax calculation, etc., any calculation that needs to be accurate to a few digits after the decimal point.
  • 🏦Scientific calculations:Science fields that require high-precision computing, such as physics, chemistry, etc.
  • 🧪Commercial Applications:Order amount calculation, inventory management, report generation, etc.
  • 📊Any scenario where floating point accuracy issues need to be avoided. 🎯

BigDecimalUsage

createBigDecimalObject:

  • BigDecimal(String val): It is recommended to use string construction method to avoid the accuracy problems caused by double. 👍
  • BigDecimal(int val)
  • BigDecimal(long val)
  • BigDecimal(double val): Not recommended, because double itself may have accuracy problems. 👎
  • (double val): The underlying layer also converts double to string and then creates BigDecimal objects, which is better than using BigDecimal(double) directly. 💡
  • BigDecimal num1 = new BigDecimal("0.1"); // Recommended
  • BigDecimal num2 = new BigDecimal(0.1);   // Not recommended
  • BigDecimal num3 = (0.1); // Recommended
BigDecimal num1 = new BigDecimal("0.1"); // recommendBigDecimal num2 = new BigDecimal(0.1);   // Not recommendedBigDecimal num3 = (0.1); // recommend

Common methods:

  • add(BigDecimal augend): addition
  • subtract(BigDecimal subtrahend): Subtraction
  • multiply(BigDecimal multiplicand): multiply
  • divide(BigDecimal divisor): division
  • divide(BigDecimal divider, int scale, RoundingMode roundingMode): division, specify precision and rounding mode.
  • setScale(int newScale, RoundingMode roundingMode): Set the precision and rounding mode.
  • compareTo(BigDecimal val): Compare size (returns -1, 0, 1, which means less than, equal to, and greater than, respectively)
  • toString(): Convert to string
  • intValue(), longValue(), floatValue(), doubleValue(): Convert to basic data type (precision may be lost) ⚠️

Rounding mode (RoundingMode):

  • : Round away from zero direction.
  • : Rounding towards zero direction.
  • : Rounding in a positive infinite direction.
  • : Rounding in the direction of negative infinity.
  • RoundingMode.HALF_UP: Rounded (greater than or equal to 0.5 carry).
  • RoundingMode.HALF_DOWN: Rounding (greater than 0.5 carry).
  • RoundingMode.HALF_EVEN: banker rounding method (round six, five, even number, odd number carry).
  • : Assertion does not require rounding, and if rounding is required, an ArithmeticException is thrown.

Sample code

import ;
import ;
public class BigDecimalExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("10.5");
        BigDecimal num2 = new BigDecimal("3.2");
        // Addition        BigDecimal sum = (num2);
        ("Sum: " + sum);
        // Subtraction        BigDecimal difference = (num2);
        ("Difference: " + difference);
        // Multiplication        BigDecimal product = (num2);
        ("Product: " + product);
        // Division (requires specified precision and rounding mode)        try {
            BigDecimal quotient = (num2, 2, RoundingMode.HALF_UP); // Keep two decimal places and round            ("Quotient: " + quotient);
        } catch (ArithmeticException e) {
            ("The division operation error:" + ());
        }
        // Set the accuracy        BigDecimal scaledNum = (1, RoundingMode.HALF_UP); // Keep one decimal and round        ("Scaled Number: " + scaledNum);
        // Compare size        int comparisonResult = (num2);
        if (comparisonResult > 0) {
            ("num1 is greater than num2");
        } else if (comparisonResult < 0) {
            ("num1 is less than num2");
        } else {
            ("num1 is equal to num2");
        }
    }
}

4. Potential issues and precautions for BigDecimal

  • Performance issues: BigDecimalOperational ratiofloatanddoubleMuch slower. 🐌 Because it requires complex calculations to ensure accuracy. Therefore, it should be used only in scenarios where precise calculations are requiredBigDecimal
  • Immutability: BigDecimalObjects are immutable. This means that each operation creates a new oneBigDecimalObject. Therefore, a lot ofBigDecimalComputing can cause performance issues and excessive memory usage. ⚠️
BigDecimal total = ;
for (int i = 0; i < 1000; i++) {
    total = (new BigDecimal("0.1")); // Create a new BigDecimal object every time the loop}
(total);

If a lot ofBigDecimalComputing, you can consider usingBigDecimalofMathContextto control precision and rounding mode, or use other optimization techniques.

  • NullPointerExceptionBigDecimalThe object can benull. In useBigDecimalBefore the object, the empty check should be performed to avoidNullPointerException。 💥
  • Division operation:When performing division operations, precision and rounding mode must be specified, otherwise it may be thrownArithmeticException(If the result is an infinite loop decimal). ➗
  • Construction method selection:Always useBigDecimal(String)or(double)Construct method to avoiddoubleThe accuracy problems brought about. 🧐
  • Comparison size:usecompareTo()Method comparison, do not use====Comparing references to objects, not values. ⚖️
  • Cache BigDecimal objects:For some commonly used BigDecimal values ​​(such as 0, 1, 10), consider using static constants to cache these objects to avoid repeated creation. ♻️
public static final BigDecimal ZERO = (0);
public static final BigDecimal ONE = (1);
public static final BigDecimal TEN = (10);

5. Summary

BigDecimalIt is an important class in Java for precise decimal calculations. It is suitable for scenarios such as finance and science that require high-precision calculations. but,BigDecimalThe calculation speed is slow, and some potential problems need to be paid attention to, such as accuracy, rounding mode,NullPointerExceptionwait. Select to useBigDecimalWhen , it is necessary to weigh the accuracy and performance, and select appropriate construction methods, calculation methods and rounding modes according to actual conditions. 👍

I hope this article can help you understand and use it betterBigDecimalkind. 🎉

This is the end of this article about the summary of BigDecimal usage in Java. For more related Java BigDecimal content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!