2012-12-14 58 views
0

我試圖將雙值格式化爲貨幣,然後刪除歐元符號但我的應用程序崩潰。有人能告訴我哪裏錯了嗎?將雙倍轉換爲字符串並刪除歐元符號貨幣

public class Formatting { 

    public static String replaceString(String text){ 

     NumberFormat formatter = NumberFormat.getCurrencyInstance(); 
     String moneyString = formatter.format(text); 
     System.out.println("epargne: "+moneyString); 

     return text.replaceAll("£", ""); 

    } 

    public static String convert(double x){ 
     return replaceString(Double.toString(x)); 

    } 

} 

我人稱其爲類如下ý

雙X = A + B + C;

System.out.println(Formatting.convert(x));

+3

什麼是例外? – PermGenError

+1

假設我有1000.009我將它轉換爲1,000.01而沒有前面的貨幣符號 – Dimitri

+1

您的代碼使用英鎊「英鎊」,而不是「歐元」。那是你的意圖嗎? – rossum

回答

4

format接受雙擊,沒有必要將該值轉換爲String。 replaceAll需要正則表達式,你可以簡單地使用replace這需要一個字符。

public static String replaceString(double value){ 
    NumberFormat formatter = NumberFormat.getCurrencyInstance(); 
    String currencySymbol = formatter.getCurrency().getSymbol(); 
    String moneyString = formatter.format(value); 
    return moneyString.replace(currencySymbol, ""); 
} 

public static String convert(double x){ 
    return replaceString(x); 
} 
+0

如果您刪除硬編碼的貨幣符號並在其位置使用適當的值,將會+1。 – Perception

+0

@Perception完成! –

1

當你不想讓貨幣回來,你可以簡單地使用DecimalFormat這也會給你(從你comment)四捨五入至小數點後2位:

public static String replaceString(double number) {  
    NumberFormat formatter = new DecimalFormat("0.00"); 
    return formatter.format(number); 
}