Java BigDecimal negate() Method with Example

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

BigDecimal Class negate() method

Syntax:

    public BigDecimal negate();
    public BigDecimal negate(MathContext ma_co);
  • negate() method is available in java.math package.
  • negate() method is used to get a negation of this BigDecimal and its scale is non-negative.
  • negate(MathContext ma_co) method is used to retrieve a negation of this BigDecimal along with rounding based on the given MathContext settings.
  • These methods may throw an exception at the time of the negation of 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, negate(),
    • It does not accept any parameter.
  • In the first case, negate(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,

  • In the first case, it returns the negation of this BigDecimal.
  • In the second case, it returns the negation of this BigDecimal. with rounding if required.

Example:

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

import java.math.*;

public class NegateOfBD {
    public static void main(String args[]) {
        // Initialize two variables val1,
        // val2 
        String val1 = "-10.30";
        int val2 = 4;

        // Initialize two BigDecimal objects and
        // one MathContext
        BigDecimal b_dec1 = new BigDecimal(val1);
        BigDecimal b_dec2 = new BigDecimal(val2);
        MathContext ma_co = new MathContext(2, RoundingMode.CEILING);

        System.out.println("negate(): ");

        // returns the negate value of this BigDecimal
        // like (-b_dec2)
        BigDecimal negate = b_dec2.negate();
        System.out.println("b_dec2.negate(): " + negate);

        System.out.println(" ");

        System.out.println("negate(MathContext): ");

        // returns the negate value of this BigDecimal
        // (-b_dec1) and return the result based on the given
        // context settings
        negate = b_dec1.negate(ma_co);
        System.out.println("b_dec1.negate(ma_co): " + negate);
    }
}

Output

negate(): 
b_dec2.negate(): -4
 
negate(MathContext): 
b_dec1.negate(ma_co): 11


Comments and Discussions!

Load comments ↻





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