Java BigDecimal abs example

Example below shows working of .abs() method of bigdecimal class. Method always returns absolute values.

Java BigDecimal abs example

Example below shows working of .abs() method of bigdecimal class. Method always returns absolute values.

Java BigDecimal abs example

Java BigDecimal abs example

     

Example below shows working of .abs() method of bigdecimal class. Method always returns absolute values. Here it returns the absolute values of bigdecimal class objects big_0 & big_1 respectively. In the example .abs() method working is demonstrated with the involvement of several other classes that are MathContext & RoundingMode classes respectively. With RoundedMode class HALF_EVEN field feature is passed into the constructor of MathContext class object mc. And then the MathContext class object mc is passed inside the parentheses of bigdecimal class .abs() method. By doing this the absolute value that the .abs() method returns is modified with rounding as per the context settings. 

Syntax for using the method : public BigDecimal abs() 
bigDecimal_objectName.abs();
bigDecimal_objectName.abs(mc);

Scale of the value will be the scale of the bigdecimal  object  i.e. this.scale.
This example is coded on the two constructor forms .abs() and .abs()(MathContext mc) respectively of method abs. 
Method throws NumberFormatException if it finds a value other than a integer or double value. 

Java_BigDecimal_abs.java

import java.math.BigDecimal;
import java.math.*; // import java.math.MathContext; //import java.math.RoundingMode;

public class Java_BigDecimal_abs {
  public static void main(String args[]) {
  // array of characters
  char ch[] '2''7''5''1''0''8''9''3''*' };
  // creating object big_0
  BigDecimal big_0;
  // defining array indexes
  big_0 = new BigDecimal(ch, 08);

  // creating BigDecimal class object big_1
  // string passed in the constructor is the value of the object big_1
  BigDecimal big_1 = new BigDecimal("100.0235");

  MathContext mc = new MathContext(2, RoundingMode.HALF_EVEN);
  // Returns the absolute value of this BigDecimal object big_0, and the
  // default scale is 'this.scale()'.
  System.out.println(".abs() value of object big_0 : " "ph[] : "
  + big_0.abs());

  // Returns the absolute value of BigDecimal object big_1 , with rounding
  // as per context settings.
  System.out.println(".abs() value of object big_1 : "
  "ph[] : "
  (big_1.abs(mc))
  "\n\n object big_1 value is in scientific form, which can evaluated as "
  "(10 * 100)/10 \n\t\twhich is equal to the police control room no."
  " (one double zero)100");
  }
}

Download the source code