Java Program to save decimal

Java 8Object Oriented ProgrammingProgramming

Let’s say the value is 0.10705921712947473 and you want to save only the first 3 decimal digits. At first let us declare the values −

double val = 320.0 / 2989.0;
BigDecimal big = new BigDecimal(val);

Now, use setScale() and set the parameter as 3 to save 3 decimal places −

big = big.setScale(3, RoundingMode.HALF_DOWN);

Example

 Live Demo

import java.math.BigDecimal;
import java.math.RoundingMode;
public class Demo {
   public static void main(String[] args) {
      double val = 320.0 / 2989.0;
      BigDecimal big = new BigDecimal(val);
      System.out.println(String.format("Value = %s", val));
      // scale
      big = big.setScale(3, RoundingMode.HALF_DOWN);
      double val2 = big.doubleValue();
      System.out.println(String.format("Scaled result = %s", val2));
   }
}

Output

Value = 0.10705921712947473
Scaled result = 0.107
raja
Published on 23-Apr-2019 08:30:14
Advertisements