Java.math.BigDecimal.negate() Method



Description

The java.math.BigDecimal.negate(MathContext mc) returns a BigDecimal whose value is (-this), with rounding according to the context settings.

Declaration

Following is the declaration for java.math.BigDecimal.negate() method.

public BigDecimal negate(MathContext mc)

Parameters

mc - The context to use.

Return Value

This method returns the negated value of the object i.e - this, rounded as necessary.

Exception

ArithmeticException − If the result is inexact but the rounding mode is UNNECESSARY.

Example

The following example shows the usage of math.BigDecimal.negate() method.

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      MathContext mc = new MathContext(4);// 4 precision

      // assign value to bg1
      bg1 = new BigDecimal("40.1264");

      // assign negate value of bg1 to bg2 using mc
      bg2 = bg1.negate(mc);

      String str = "Negated value, rounded to 2 precision is " +bg2;

      // print bg2 value
      System.out.println( str );
   }
}

Let us compile and run the above program, this will produce the following result −

Negated value, rounded to 2 precision is -40.13
java_math_bigdecimal.htm
Advertisements