我有一个代表一美元金额的字符串,我正在尝试使用.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);
}
Run Code Online (Sandbox Code Playgroud)
注意:MoneyFormat是使用getCurrencyInstance()初始化的NumberFormat对象.
replaceAll接受正则表达式.在正则表达式中,$是一个字符串结尾的锚点,所以你必须将其转义才能将其用作美元符号:
.replaceAll("\\$", "");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |