convert very small double to a String
I have a very small number and I want to convert it to a String with the full n开发者_如何学Goumber, 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.
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));
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.
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.
Have a look at: http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern
I think the format "0.####" might work.
精彩评论