Reputation: 407
Using DecimalFormat gives no parse exception when using this kind of number:
123hello
which is obviously not really a number, and converts to 123.0 value. How can I avoid this kind of behaviour?
As a side note hello123 does give an exception, which is correct.
Thanks, Marcel
Upvotes: 13
Views: 1977
Reputation: 53694
Expanding on @Kal's answer, here's a utility method which you can use with any formatter to do "strict" parsing (uses apache commons StringUtils):
public static Object parseStrict(Format fmt, String value)
throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Object result = fmt.parseObject(value, pos);
if(pos.getIndex() < value.length()) {
// ignore trailing blanks
String trailing = value.substring(pos.getIndex());
if(!StringUtils.isBlank(trailing)) {
throw new ParseException("Failed parsing '" + value + "' due to extra trailing character(s) '" +
trailing + "'", pos.getIndex());
}
}
return result;
}
Upvotes: 2
Reputation: 68847
You can verify it is numeric using a RegEx:
String input = "123hello";
double d = parseDouble(input); // Runtime Error
public double parseDouble(String input, DecimalFormat format) throws NumberFormatException
{
if (input.equals("-") || input.equals("-."))
throw NumberFormatException.forInputString(input);
if (!input.matches("\\-?[0-9]*(\\.[0-9]*)?"))
throw NumberFormatException.forInputString(input);
// From here, we are sure it is numeric.
return format.parse(intput, new ParsePosition(0));
}
Upvotes: 0
Reputation: 24910
To do exact parsing, you can use
public Number parse(String text,
ParsePosition pos)
Initialize pos to 0 and when its finished it will give you the index after the last character that was used.
You can then compare this against string length to make sure the parse was accurate.
Upvotes: 10