In the case where you don't know the locale of the string value received and it is not necessarily the same locale as the current default locale you can use this :
private static double parseDouble(String price){
String parsedStringDouble;
if (price.contains(",") && price.contains(".")){
int indexOfComma = price.indexOf(",");
int indexOfDot = price.indexOf(".");
String beforeDigitSeparator;
String afterDigitSeparator;
if (indexOfComma < indexOfDot){
String[] splittedNumber = price.split("\\.");
beforeDigitSeparator = splittedNumber[0];
afterDigitSeparator = splittedNumber[1];
}
else {
String[] splittedNumber = price.split(",");
beforeDigitSeparator = splittedNumber[0];
afterDigitSeparator = splittedNumber[1];
}
beforeDigitSeparator = beforeDigitSeparator.replace(",", "").replace(".", "");
parsedStringDouble = beforeDigitSeparator+"."+afterDigitSeparator;
}
else {
parsedStringDouble = price.replace(",", "");
}
return Double.parseDouble(parsedStringDouble);
}
It will return a double no matter what the locale of the string is. And no matter how many commas or points there are. So passing 1,000,000.54
will work so will 1.000.000,54
so you don't have to rely on the default locale for parsing the string anymore. The code isn't as optimized as it can be so any suggestions are welcome. I tried to test most of the cases to make sure it solves the problem but I am not sure it covers all. If you find a breaking value let me know.
replaceAll(",",".")
replaces all commas with dots. If there are no commas, then it does nothing.Double.valueOf()
works (only) with strings that use dot as decimal separator. Nothing here is affected by current default locale. docs.oracle.com/javase/8/docs/api/java/lang/… – BaronialreplaceAll(",",".")
is that it'll only work if there is a single comma: ie: 1,234,567 will throwjava.lang.NumberFormatException: multiple points
. A regex with positive lookahead will sufficep.replaceAll(",(?=[0-9]+,)", "").replaceAll(",", ".")
More at: regular-expressions.info/lookaround.html – Retaliation