2010-03-15 47 views
3

SO上有一個類似的問題,它建議使用NumberFormat,這是我所做的。將科學計數法轉換成十進制表示法

我正在使用NumberFormat的parse()方法。

public static void main(String[] args) throws ParseException{ 

    DecToTime dtt = new DecToTime(); 
    dtt.decToTime("1.930000000000E+02"); 

} 

public void decToTime(String angle) throws ParseException{ 

    DecimalFormat dform = new DecimalFormat(); 
    //ParsePosition pp = new ParsePosition(13); 
    Number angleAsNumber = dform.parse(angle); 

    System.out.println(angleAsNumber); 
} 

結果我得到的是

1.93

我真的沒有想到這個工作,因爲1.930000000000E + 02是一個非常不尋常找數,我必須首先做一些字符串解析來刪除零?還是有一個快速和優雅的方式?

回答

2

當您在科學記數法中對錶達式使用DecimalFormat時,您需要指定一個模式。嘗試像

DecimalFormat dform = new DecimalFormat("0.###E0"); 

查看javadocs for DecimalFormat - 有一個標有「Scientific Notation」的部分。

1

如果你把你的角度看作雙重的而不是字符串,你可以使用printf魔法。

System.out.printf("%.2f", 1.930000000000E+02);

顯示浮子爲2位小數。 193.00

如果改爲使用"%.2e"作爲格式說明,你會得到"1.93e+02"

(不知道正是你想要的輸出,但它可能會有所幫助。)

3

背誦String.format語法,這樣你就可以轉換您的雙打和BigDecimals的無論何種精密串無E符號:

這java代碼:

double dennis = 0.00000008880000d; 
System.out.println(dennis); 
System.out.println(String.format("%.7f", dennis)); 
System.out.println(String.format("%.9f", new BigDecimal(dennis))); 
System.out.println(String.format("%.19f", new BigDecimal(dennis))); 

打印:

8.88E-8 
0.0000001 
0.000000089 
0.0000000888000000000 
相關問題