我正在尋找一種有效的方法,讓String
的數字格式正確,因此可以將其解析爲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;
}
的String.format(...)? – tbsalling