0

有一種情況是我正在閱讀webelement中的貨幣,它是一個字符串。需要將其轉換爲數字格式,以便計算一些P & L.從webelement讀取字符串,並將其轉換爲小數點

嘗試下面的代碼

public class NumberFormat { 

    public static void main(String[] args) { 
     //String str = "$9.9967"; 
     String str1 = "€12,32123"; 
     String str2 = "€3.452,35"; 
     str1 = str1.replace(",", ".").replace(".", "").replaceAll("[^0-9.]", ""); 
     str2 = str2.replace(",", ".").replace(".", "").replaceAll("[^0-9.]", ""); 
     double str1Ch = Double.parseDouble(str1); 
     double str2Ch = Double.parseDouble(str2); 
     System.out.println(str1Ch); 
     System.out.println(str2Ch); 
    } 

} 

實際結果:

1232123.0 
345235.0 

預期結果:

12.32123 
3452.35 

,我沒有得到我所期待的,我需要執行兩個轉換同步(點空/空,逗點點)

需要知道爲什麼代碼不能正常工作,以及閱讀不同國家貨幣並將其轉換爲數字格式的建議。

+1

什麼是預期的結果? –

+0

12.32123 3452.35 –

+0

您應該用'NumberFormat'類轉換貨幣字符串。看到這裏的信息https://stackoverflow.com/a/6016642/1967021 –

回答

2

一個選項可以創建這樣做你自己NumberFormat(此基於DecimalFormat)。您可以使用DecimalFormatSymbols設置其小數點分隔符或分組分隔符號。

演示:

DecimalFormat df = new DecimalFormat("€#,###.#"); 
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols(); 
dfSymbols.setDecimalSeparator(','); 
dfSymbols.setGroupingSeparator('.'); 
df.setDecimalFormatSymbols(dfSymbols); 

String str1 = "€12,32123"; 
String str2 = "€3.452,35"; 
double str1Ch = df.parse(str1).doubleValue(); 
double str2Ch = df.parse(str2).doubleValue(); 

System.out.println(str1Ch);//12.32123 
System.out.println(str2Ch);//3452.35 
1

您混淆了符號逗號和句號的替換。

即先用空字符串替換句點,然後用句點替換逗號。如下所示。

str1 = str1.replace(".", "").replace(",", ".").replaceAll("[^0-9.]", ""); 
    str2 = str2.replace(".", "").replace(",", ".").replaceAll("[^0-9.]", ""); 
+0

感謝@RinorNeedsHelp,它的工作。 –

-1

試試這個。

String str1 = "€12,32123"; 
String str2 = "€3.452,35"; 
str1 = str1.replaceAll("[^0-9,]", "").replace(",", "."); 
str2 = str2.replaceAll("[^0-9,]", "").replace(",", "."); 
double str1Ch = Double.parseDouble(str1); 
double str2Ch = Double.parseDouble(str2); 
System.out.println(str1Ch); 
System.out.println(str2Ch); 

結果

12.32123 
3452.35 
1

可以使用NumberFormat

String s1 = "€3.452,35"; 

Locale locale = null; 
switch (s1.charAt(0)) { 
    case '€': 
     locale = Locale.FRANCE; 
     break; 
    case '$': 
     locale = Locale.US; 
     break; 
    //Add any other money you want 
    default: 
     //Money unexpected 
} 

s1 = s1.substring(1, s1.length()) 
     .replaceAll("[. ]", "") 
     .replaceAll(",", "."); 
System.out.println(s1); 
NumberFormat nf = NumberFormat.getCurrencyInstance(locale); 
System.out.println(nf.format(new BigDecimal(s1))); 
+0

thanks.Tried但getCurrencyInstance或任何其他方法不顯示。從我身邊出現問題嗎? –

相關問題