Java Program to save decimal


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

491 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements