我正在寻找一种有效的方法来正确设置数字String
的格式,以便可以将其解析为double
值。
要求:
- 忽略不仅包含数字、逗号 (,) 或点 (.) 的字符串;
- 重新格式化数字字符串,以便可以使用以下命令将其解析为 double 值:
Double.parseDouble(numberString);
- 当输入字符串无效时抛出 NumberFormatException
示例:1.234.567,89 => 1234567.89; 5 => 5; 6.3 => 6.3; 5.23 => 5.23;...
要检查String
是否是数字,我想使用正则表达式或NumberUtils.isNumber(numberString)
。后一个的唯一问题是它与“123,45”等字符串存在问题。
我当前的尝试(感觉效率很低):
LOGGER.debug("Normalizing price string: " + price);
String str = price;
if (str.contains(",") || str.contains(".")) {
int pos = -1;
if (str.contains(",")) pos = str.lastIndexOf(',');
else if (str.contains(".")) pos = str.lastIndexOf(".");
//Remove all the dots and commas first
str = str.replaceAll("[,.]", "");
if (!NumberUtils.isNumber(str) || !NumberUtils.isDigits(str)) {
LOGGER.debug("String does not match expected pattern");
throw new NumberFormatException();
} else {
//Add a dot back in
if (str.length() <= 2) {
StringBuilder first = new StringBuilder(str.substring(0, pos));
first.append('.');
String last = str.substring(pos);
str = first + last;
} else {
StringBuilder first = new StringBuilder(str.substring(0, str.length() - 2));
first.append('.');
String last = str.substring(str.length() - 2);
str = first + last;
}
}
}
LOGGER.debug("Normalised result: " + str);
return str;`
如何简化这种格式、提高效率并正确处理不正确的输入?
应用的解决方案
String str = price;
DecimalFormatSymbols dfsDot = new DecimalFormatSymbols();
dfsDot.setDecimalSeparator('.');
DecimalFormatSymbols dfsComma = new DecimalFormatSymbols();
dfsComma.setDecimalSeparator(',');
DecimalFormat dfDot = new DecimalFormat("#,##0.00", dfsDot);
DecimalFormat dfComma = new DecimalFormat("#,##0.00", dfsComma);
double d = 0;
try {
if (!str.contains(",") && !str.contains(".")) {
return str;
} else if (str.contains(",")) d = (Double) dfComma.parse(str);
else if (str.contains(".")) d = (Double) dfDot.parse(str);
str = "" + d;
} catch (ParseException e) {
LOGGER.debug(str + " couldn't be cast to Double");
e.printStackTrace();
return price;
}
最佳答案
你知道DecimalFormat
吗?
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("#,##0.00",dfs);
double d = df.parse("123.45").doubleValue();
System.out.println(d);
它打印:
123.45
关于java - 如何正确格式化数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095988/