Create a BigDecimal via string in Java

Java 8Object Oriented ProgrammingProgramming

Let us see how we can create BigDecimal values via string. Here, we have set string as a parameter to the BigDecimal constructor.

BigDecimal val1 = new BigDecimal("375789755.345778656");
BigDecimal val2 = new BigDecimal("525678755.155778656");

We can also perform mathematical operations on it −

val2 = val2.subtract(val1);

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("375789755.345778656");
      BigDecimal val2 = new BigDecimal("525678755.155778656");
      System.out.println("Value 1 : "+val1);
      System.out.println("Value 2 : "+val2);
      val2 = val2.subtract(val1);
      System.out.println("Result (Subtraction) = "+val2);
   }
}

Output

Value 1 : 375789755.345778656
Value 2 : 525678755.155778656
Result (Subtraction) = 149888999.810000000
raja
Published on 20-Dec-2018 11:11:15
Advertisements