12

if

double d =  1.999e-4

I want my output to be 0.0001999.

How can I do it?

hibc
  • 267
  • 1
  • 5
  • 12

5 Answers5

9
NumberFormat formatter = new DecimalFormat("###.#####");  

String f = formatter.format(d);  

You can explore the sub classes of NumberFormat class to know more details.

RP-
  • 5,827
  • 2
  • 27
  • 46
7

I suppose there is a method in BigDecimal Class called toPlainString(). e.g. if the the BigDecimal is 1.23e-8 then the method returns 0.0000000124.

BigDecimal d = new BigDecimal("1.23E-8");

System.out.println(d.toPlainString());

Above code prints 0.0000000123, then you can process the string as per your requirement.

himawan_r
  • 1,760
  • 1
  • 14
  • 22
  • my excelsheet number is 42.063706, but returns 42.06370600000000337104211212135851383209228515625 – Abdullah Nurum Feb 26 '18 at 18:08
  • @AbdullahNurum what method are you using to read in the excel sheet and construct the BigDecimal object? When I construct it with the string literal "42.063706" it outputs the correct thing (same as input). Make sure you aren't storing it in a floating point value in between reading and making the BigDecimal object. You should keep it as a string during that time, in order to not lose precision. – theferrit32 May 29 '19 at 23:51
5

You can do it like this:

    double d = 1.999e-4;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(7);
    System.out.println(nf.format(d));

Check out the documentation of NumberFormat's methods to format your double as you see fit.

DecimalFormat is a special case of NumberFormat as its constructor states, I don't think that you need its functionality for your case. Check out their documentation if you are confused. Use the factory method getInstance() of NumberFormat for your convenience.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
3

If all you want is to print like that.

System.out.printf("%1$.10f", d);

you can change 10f, 10=number of decimal places you want.

specialscope
  • 4,188
  • 3
  • 24
  • 22
  • Thank you very much! what does 1$ = ?? – hibc Oct 25 '12 at 08:39
  • 1$=argument index, if you had System.out.printf("%3$.10f", e,f,d); you would use 3$ as your target is d. Details here. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html – specialscope Oct 25 '12 at 09:02
0

Take a look over

java.text.DecimalFormat

and

java.text.DecimalFormatSymbols
cmg_george
  • 309
  • 1
  • 2
  • 9