Java BigDecimal add() Method with Example

BigDecimal Class add() method: Here, we are going to learn about the add() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 05, 2020

BigDecimal Class add() method

Syntax:

    public BigDecimal add(BigDecimal val);
    public BigDecimal add(BigDecimal val, MathContext ma_co);
  • add() method is available in java.math package.
  • add(BigDecimal val) method is used to get a BigDecimal that holds the value added this BigDecimal with the given BigDecimal and its scale is calculated by using max([this BigDecimal.scale()] , [BigDecimal val.scale()]).
  • add(BigDecimal val, MathContext ma_co) method is used to get a BigDecimal that holds the value-added this BigDecimal with the given BigDecimal based on the given MathContext settings.
  • These methods may throw an exception at the time of adding an object.
    ArithmeticException: This exception may throw when the result is not accurate and set the rounding mode "UNNECESSARY".
  • These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, add(BigDecimal val),
    • BigDecimal val – represents the object is to add with this BigDecimal object.
  • In the first case, abs(MathContext ma_co),
    • BigDecimal val – Similar as defined in the first case.
    • MathContext ma_co – represents the context setting to use in rounding.

Return value:

In both the cases, the return type of the method is BigDecimal,

  • In the first case, it returns the added result of both the objects without any context setting.
  • In the second case, it returns the added result of both the objects with any context setting.

Example:

// Java program to demonstrate the example 
// of add() method of BigDecimal

import java.math.*;

public class AddOfBD {
    public static void main(String args[]) {
        // Initialize two variables - val,
        // and str 
        int val = 120;
        String str = "2.357";

        // Initialize two BigDecimal objects and
        // one MathContext
        BigDecimal b_dec1 = new BigDecimal(val);
        BigDecimal b_dec2 = new BigDecimal(str);
        MathContext ma_co = new MathContext(5, RoundingMode.CEILING);


        // add this BigDecimal b_dec1 with the given
        // BigDecimal b_dec2
        BigDecimal add_val = b_dec1.add(b_dec2);
        System.out.println("b_dec1.add(b_dec2): " + add_val);

        // add this BigDecimal b_dec1 with the given
        // BigDecimal b_dec2 based on the given context
        // settings
        add_val = b_dec1.add(b_dec2, ma_co);
        System.out.println("b_dec1.add(b_dec2, ma_co): " + add_val);
    }
}

Output

b_dec1.add(b_dec2): 122.357
b_dec1.add(b_dec2, ma_co): 122.36


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.