Negate a BigDecimal value in Java


Use the negate() method to negate a BigDecimal value in Java. The method returns a BigDecimal whose value is (-this), and whose scale is this.scale().

The following is an example −

Example

 Live Demo

import java.math.BigDecimal;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BigDecimal val1 = new BigDecimal("37578975587");
      BigDecimal val2 = new BigDecimal("62567875598");
      System.out.println("Value 1 : "+val1);
      System.out.println("Value 2 : "+val2);
      // division
      val1 = val2.negate();
      System.out.println("Result (Negation) = "+val1);
   }
}

Output

Value 1 : 37578975587
Value 2 : 62567875598
Result (Negation) = -62567875598

Let us see another example −

Example

 Live Demo

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigDecimal bg1, bg2;
      bg1 = new BigDecimal("68.99898");
      bg2 = bg1.negate();
      String str = "Negated value of " + bg1 + " is "+ bg2;
      System.out.println( str );
   }
}

Output

Negated value of 68.99898 is -68.99898

Updated on: 30-Jul-2019

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements