0

How to round off double to have max n number of digits including digits before and after decimal point.

Format : Numeric (10,8) [a maximum of 10 numeric digits, with up to 8 digits after the decimal place.

Example:

2233.64344206d should round to 2233.643442d.

2233.64344206d has 4 digits before decimal point, 8 after, total 12 digits, and there should be a maximum of 10 total digits. So 2233.643442d is the correct rounding result, because it has 4 digits before decimal point, 6 after, for a total of 10 digits.

java.text.DecimalFormat works to round of number after decimal point. eg if i want to round off number to have max 4 digits after decimal point then i can use DecimalFormat("#0.####")

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70
Suvasis
  • 1,431
  • 1
  • 24
  • 40
  • You should consider converting your double to BigDecimal and using setScale() method. – Abhijeet Sep 14 '16 at 09:23
  • Do you need the rounded value for further processing, or do you just want to print the value? – Michael Piefel Sep 14 '16 at 09:39
  • @Michael : round off value will be sent via xml tag to different system. – Suvasis Sep 14 '16 at 09:42
  • @EJP that's not what he wants, just had a discussion and the question is clearer now. The question is how to round on the total number of digits (before and after decimal point together). That's not covered by the suggested duplicate (I already mentioned that question in a comment that I deleted after the question became clearer) – Erwin Bolwidt Sep 14 '16 at 09:47

1 Answers1

0

You can use BigDecimal, look at how many digits you need before the decimal point, look at the total number of digits that you want, and set the scale to the difference between these:

public static void main(String[] args) {
    double p = 2233.64344206d;
    BigDecimal d = new BigDecimal(p);
    int n = 10;
    int integralDigits = d.toBigInteger().toString().length();
    d = d.setScale(n - integralDigits, RoundingMode.HALF_EVEN);
    System.out.println(d);
}

Output: 2233.643442

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70