2016-04-27 34 views
0

我有一個字符串建立這樣的:在字符串轉換的指數值轉換爲十進制表示沒有指數形式

String str = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526" 

還有就是-7.5e-4,我想變成-0.00075

我想指數值更改爲十進制值以獲得這樣的事情:

String str = "m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526" 

我有很多像這樣的字符串來檢查和轉換。

我真的不知道該如何有效地改變指數值,因爲所有這些值是一個字符串...

如果你知道一個高效,快捷的方式做到這一點,請告訴我。

+0

嘗試使用https://docs.oracle.com/javase/7/docs/api/java/math/ BigDecimal.html#BigDecimal(java.lang.String) –

+0

先試試然後問 –

+0

謝謝,我問,因爲我不知道該怎麼做。你的回答非常有幫助。 – Beginner

回答

1

像這樣的東西應該做的工作:

public static void main(String[] args) { 
    String patternStr = "[0-9.-]*e[0-9.-]*"; 
    String word = "m -263.61653,-131.25745 c -7.5e-4,-1.04175 0.71025,-1.90875 1.67025,-2.16526"; 
    Pattern pattern = Pattern.compile(patternStr); 
    Matcher matcher = pattern.matcher(word); 
    if (matcher.find()) { 
     Double d = Double.valueOf(matcher.group()); 
     System.out.println(word.replaceAll(patternStr, BigDecimal.valueOf(d).toPlainString())); 
    } 

} 

輸出將是:

m -263.61653,-131.25745 c -0.00075,-1.04175 0.71025,-1.90875 1.67025,-2.16526 

當然如果字符串中存在多個指數,則必須稍微調整一下。

+0

謝謝!它像一個魅力。我會適應它,因爲我有時會在字符串上有多個指數。感謝你的寶貴時間。 – Beginner

3

您可以使用該方法toPlainStringBigDecimal類:

String num = "7.5e-4"; 
new BigDecimal(num).toPlainString();//output 0.00075 
0

您可以Double.parseDouble解析,然後用的String.format()格式:

double d = Double.parseDouble("-7.5e-4"); 
    String s = String.format("%f", d); 
相關問題