Search code examples
javadecimalformatparseexception

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


Solution

  • 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