Java BigDecimal Class

Profile picture for user arilio666

In this article, we will see BigDecimal and how it works.

Java BigDecimal is a class in the Java programming language that provides support for arbitrary-precision decimal arithmetic. It is used to do arithmetic operations on numbers with high precision and accuracy, which is particularly important for financial calculations where accuracy is crucial.

Why BigDecimal?

  1. The BigDecimal class provides various methods for performing arithmetic operations, like , multiplication, subtraction, addition and division.
  2. It also provides rounding methods, comparing and converting BigDecimal values to other data types.

To create a BigDecimal object, you can use one of the following constructors:

  • BigDecimal(String) - creates a BigDecimal object from a string representation of a decimal number.
  • BigDecimal(double) - creates a BigDecimal object from a double value. This constructor is not recommended, as it can result in inaccuracies due to the limited precision of double values.
  • BigDecimal(BigInteger) - creates a BigDecimal object from a BigInteger value.
  • BigDecimal(long) - creates a BigDecimal object from a long value.
        BigDecimal num1 = new BigDecimal("10333333.5");
        BigDecimal num2 = new BigDecimal("203333.75");
        BigDecimal result = num1.add(num2);
        BigDecimal multiply = num1.multiply(num2);
        String stringres = result.toString();
        System.out.println(multiply);
        
  • In this example, we have used the add and multiply, extracted the value, and converted it to string. This can be done, and one of the reasons to use BigDecimal.

        
Java BigDecimal Class
 

  • As we can see, here is the list of all the available methods available in the Bigdecimal class.
Tags