2013-05-18 21 views
0

上工作我有一個代表美元金額的字符串,並試圖使用.replaceAll(「$」,「」)來準備它以便與parseDouble()一起使用。但是,當我運行我的應用程序時,我仍然得到java.lang.NumberFormatException: Invalid double: "$100.00",所以無論出於何種原因,replaceAll()都不起作用。誰能建議爲什麼

這裏的影響的代碼塊:

public String subtractCurrenciesToString(String value1, String value2){ 
    String stringValue1 = value1.replaceAll("$", ""); 
    String stringValue2 = value2.replaceAll("$", ""); 

    Double currency1 = Double.parseDouble(stringValue1); 
    Double currency2 = Double.parseDouble(stringValue2); 

    return MoneyFormat.format(currency1 - currency2); 
} 

注:MoneyFormat是()與getCurrencyInstance初始化的的NumberFormat對象。

+0

對於它的價值,如果你正在做的任何計算你的錢值你真的不應該使用Double來存儲它。看到這裏爲一個偉大的解釋爲什麼:http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – FoamyGuy

+0

有趣的閱讀Foamy,謝謝。儘管如此,只要我在存儲數據之前四捨五入,就可以避免數字錯誤發生大量分歧的危險。 – Argus9

回答

6

replaceAll接受正則表達式。在正則表達式,$是結束串錨,所以你要逃避它以字面上使用它作爲一個美元符號:

.replaceAll("\\$", ""); 
+0

這是有道理的,但我試過你提到的更正,當我parseDouble()時,我仍然在我的字符串中獲取$。 – Argus9

相關問題