0

I have a application which reads SAS xpt file and stores column value into ByteBuffer and then using getValue() method of it to get Double object. Now I have to print Double upto 12 significant digit after decimal. I found one answer from this from which is working fine but few cases

BigDecimal bd = new BigDecimal(dblColumnData.doubleValue());
System.out.println(String.format("%."+15+"G", bd));

Here 15 is given because there are 3 digits in integer part and there must be 12 significant digit after decimal.

Cases where it is not working is because BigDecimal created from Double. If I print Double then it contains more than 12 digits after decimal and it round correctly with same above approach.

Therefore I think if I can get similar format method for Double the it will solve my problem.

akash
  • 22,664
  • 11
  • 59
  • 87
Shailesh
  • 405
  • 1
  • 5
  • 18
  • Do you really mean *significant* digits? I.e. `123456.123456` contains 12 significant digits, but only 6 decimal places. I suspect you mean that you need 12 decimal places? – Duncan Jones May 20 '14 at 07:33
  • Looks like @EJP is convinced it's decimal places :-) – Duncan Jones May 20 '14 at 07:36
  • What other methods does dblColumnData have? It seems likely that you should properly be converting it to BigDecimal in some other way without going through double. – Louis Wasserman May 20 '14 at 07:45
  • @Duncan yes I mean 12 places after decimal. If i pass just 12 then format method is just returning 9 digit after decimal so I am passing 15 and returning correct values – Shailesh May 20 '14 at 08:39

1 Answers1

-1

I'd do it somehow like this:

static double roundTo(double d, int digit) {
    double exp = Math.pow(10, digit);
    d *= exp;
    d = Math.round(d);
    return d / exp;
}

The following would round the number to 3 places after the comma and print it

public static void main(String[] args) {
    System.out.println(roundTo(7.34343434, 3));
}

Will print "7.343"

Prior99
  • 619
  • 5
  • 13