我遇到了错误或其他问题。我有一个保存文章的方法,如下所示:
class SaveArticleListener implements ActionListener {
//....
String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
double price = Double.parseDouble(s);
//....
}
其中textArticlePrice
是一个JFormattedTextField
,其配置如下:
NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);
在 parseDouble
方法中我每次都会得到:
java.lang.NumberFormatException: For input string: "123 456 789.00"
所以replace
适用于点,但不适用于空格...为什么?
最佳答案
您最好使用 NumberFormat
来解析 String
。保留对 priceFormat
的引用,然后使用
double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();
用于显示数字的格式化程序与用于将其转换回 double
的格式化程序相同,因此您知道它将以兼容的方式解析它。
最重要的是
double price = ((Number) textArticlePrice.getValue()).doubleValue();
如果您正确设置了 JFormattedTextField
,则无需任何转换即可工作。 (getValue()
调用返回一个 Object
,因此您需要对其进行强制转换。它可能返回一个 Double
或 Long
,具体取决于文本字段中的内容,因此从中获取 double
的安全方法是将其视为 Number
,它是两者,并调用其 .doubleValue()
方法。)
编写一些内容将其转换为可以由 Double.parseDouble()
解析的内容确实不是正确的方法,因为如果稍后文本字段的格式发生更改,它就太脆弱了。
关于java - 从 JFormattedTextField 解析 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264188/