Java BigDecimal abs() Method with Example

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

BigDecimal Class abs() method

Syntax:

    public BigDecimal abs();
    public BigDecimal abs(MathContext ma_co);
  • abs() method is available in java.math package.
  • abs() method is used to get a BigDecimal that holds the absolute value of this BigDecimal.
  • abs(MathContext ma_co) method is used to get a BigDecimal and its value is the absolute value of this BigDecimal based on the given MathContext settings.
  • These methods may throw an exception at the time of returning an absolute value.
    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, abs(),
    • It does not accept any parameter.
  • In the first case, abs(MathContext ma_co),
    • 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, it returns the absolute value of the BigDecimal and rounding based on the default or context setting.

Example:

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

import java.math.*;
public class AbsOfBD {
    public static void main(String args[]) {
        // Initialize two variables val,
        // and str 
        String val = "-100.52";
        String str = "-2.346";

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

        // returns the BigDecimal that holds 
        // the absolulte value of this BigDecimal
        // b_dec1
        BigDecimal abs_val = b_dec1.abs();
        System.out.println("b_dec1.abs(): " + abs_val);

        // returns the BigDecimal that holds 
        // the absolulte value of this BigDecimal
        // b_dec2 based on the given context
        // settings
        abs_val = b_dec2.abs(ma_co);
        System.out.println("b_dec2.abs(ma_co): " + abs_val);
    }
}

Output

b_dec1.abs(): 100.52
b_dec2.abs(ma_co): 2.35


Comments and Discussions!

Load comments ↻





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