How can I set a specific decimal separator for a double? The next method should parse the string version of a double only if the separator is the given value, but works for both, DOT or COMMA. I want it to return true only if the string has the given separator.
public static boolean isValid(char decimalSeparator) {
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(decimalSeparator);
df.setDecimalFormatSymbols(symbols);
try {
df.parse("22,22").doubleValue();
return true;
} catch (ParseException e) {
return false;
}
}
Here is the problem. The javadoc for parse(String)
says
"Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string. "
When you provide a string with the "wrong" decimal separator, this parse method will stop when it gets to this character, and (probably) return a Long
value rather than a Double
value. A ParseException
is only thrown if the first unexpected character is the first character of the string.
The solution is to use the two argument parse
method ( javadoc ):
ParsePosition pp = new ParsePosition(0);
String str = "22,22";
df.parse(str, pp);
return pp.getIndex() == str.length() && pp.getErrorIndex() == -1;
Note that this overload of parse
does not throw ParseException
Does this help you?
public static void main(String[] args) {
isValid("22,22", ",");
isValid("22.22", ".");
isValid("2222", ",");
isValid("2222", ".");
isValid(",22", ",");
isValid("22,", ",");
isValid("22,22", ".");
}
static boolean isValid(String number, String ds) {
ds = ds.replace(".", "\\.");
String[] parts = number.split(ds);
try {
switch (parts.length) {
case 0: Integer.parseInt(number); break;
case 1: Integer.parseInt(parts[0]); break;
case 2: Integer.parseInt(parts[0]); Integer.parseInt(parts[1]); break;
default: throw new NumberFormatException();
}
return true;
} catch(NumberFormatException e) {
return false;
}
}
you may add extra conditions, like check the decimal-separator's length if it has only one char, or if ",22" can be "0,22"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.