2010-01-20 117 views
5

我有一個非常小的數字,我想將其轉換爲具有完整數字的字符串,而不是以任何方式縮寫。我不知道這個數字有多小。將非常小的雙倍轉換爲字符串

例如,當我運行:

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

它顯示1.0E-10代替0.000000001。我已經試過NumberFormat.getNumberInstance(),但它的格式爲0。我不知道在DecimalFormat上使用什麼表達式來處理任何數字。

+2

但是如果打印'1e-300',你想要什麼? 300零? – kennytm 2010-01-20 18:18:25

回答

10

假設你想在你的電話號碼的前500個零,當你做:

double d = 1E-500; 

那麼你可以使用:

double d = 1E-10; 
NumberFormat nf = NumberFormat.getInstance(); 
nf.setMaximumFractionDigits(Integer.MAX_VALUE); 
System.out.println(nf.format(d)); 
+0

僅供參考:最小的雙精度數字是〜'5e-324'。 – kennytm 2010-01-20 19:36:34

+0

謝謝,我不知道。 順便說一句,你從哪裏得到這個數字? – ryanprayogo 2010-01-20 19:44:14

+0

http://en.wikipedia.org/wiki/Double_precision_floating-point_format#IEEE_754_double_precision_binary_floating-point_format:_binary64 – kennytm 2010-01-21 03:55:33

3

您可以使用setMinimumFractionDigitssetMaximumFractionDigits來設置數字格式小數的最大和最小位數。應該解決這個問題。

2

可以使用與BigDecimals的做它在Java 5中:

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

請注意,如果您將double值作爲字符串放在第一位,則最好使用:

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

......正如BigDecimal javadocs中所解釋的那樣。