Strict number parsing

From Shrubbery

Jump to: navigation, search


The NumberFormat classes that come with the JDK don't allow for strict number parsing. This has been filed as an enhancement here: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6431200 where a workaround is listed.


"Use a ParsePosition to get the index after parsing. If ParsePostion.getIndex() != string.length(), then parse() didn't consume the entire string."

Actually, you can also add a check to make sure the error index is -1. Values other than -1 mean that there was an error. Trimming the value before parsing is also a good idea. The end product might look something like this:

    public static Number parseNumber(String value,NumberFormat format)
    {
        value = value.trim();
        ParsePosition pos = new ParsePosition(0);
        Number number = format.parse(value, pos);
        boolean okay = pos.getIndex() == value.length() && pos.getErrorIndex() == -1;
        if (!okay)
            throw new ParseException("Could not parse '" + value + "' as a number",pos.getErrorIndex());
        return number;
    }
Personal tools