Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat converts numbers with non-digits

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

like image 664
marcel Avatar asked Jul 06 '11 17:07

marcel


People also ask

What is number format and DecimalFormat class?

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.

What is DecimalFormat?

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.

What is decimal format used for?

DecimalFormat class is used for formatting numbers as per customized format and as per locale.


2 Answers

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

like image 123
Kal Avatar answered Oct 02 '22 12:10

Kal


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;
}
like image 26
jtahlborn Avatar answered Oct 02 '22 13:10

jtahlborn