views:

250

answers:

4

hi,

I have a very small number and I want to convert it to a String with the full number, not abbreviated in any way. I don't know how small this number can be.

for example, when I run:

double d = 1E-10;
System.out.println(d);

it shows 1.0E-10 instead of 0.000000001.

I've already tried NumberFormat.getNumberInstance() but it formats to 0. and I don't know what expression to use on a DecimalFormat to work with any number.

A: 

Have a look at: http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern

I think the format "0.####" might work.

Freiheit
it didn't work :( it prints `0`.
cd1
Try "0.#############"
mpez0
+3  A: 

You can set the maximum and minimum number of digits in the fraction of a numberformatter with setMinimumFractionDigits and setMaximumFractionDigits. that should fix the problem.

twolfe18
+6  A: 

Assuming that you want 500 zeroes in front of your number when you do:

double d = 1E-500;

then you can use:

double d = 1E-10;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(Integer.MAX_VALUE);
System.out.println(nf.format(d));
ryanprayogo
FYI: The smallest double-precision number is ~ `5e-324`.
KennyTM
Thanks, I didn't know that.BTW, where did you get this number from?
ryanprayogo
@ryanprayogo: http://en.wikipedia.org/wiki/Double_precision_floating-point_format#IEEE_754_double_precision_binary_floating-point_format:_binary64
KennyTM
+1  A: 

You can do it with BigDecimals in Java 5 using:

System.out.println(new java.math.BigDecimal(Double.toString(1E-10)).stripTrailingZeros().toPlainString());

Note that if you have the double value as a String in the first place, you would be better off using:

System.out.println(new java.math.BigDecimal("1E-10").toPlainString());

... as explained in the BigDecimal javadocs.

Carl Desborough