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
DecimalFormat class is subclass of NumberFormat class and it is used to format numbers by using specify formatting pattern. We can format a number upto 2 decimal place,upto 3 decimal place, using comma to separate digits.
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.
DecimalFormat class is used for formatting numbers as per customized format and as per locale.
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.
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#parse%28java.lang.String,%20java.text.ParsePosition%29
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With