averbraeck / djunits

Delft Java UNIT System for using strongly-typed quantities and units
BSD 3-Clause "New" or "Revised" License
1 stars 0 forks source link

Allow starting "+" sign for values to be parsed in valueOf() method #7

Closed averbraeck closed 1 year ago

averbraeck commented 1 year ago

The valueOf() method of scalars currently does not allow a starting '+' sign, since that is not part of the official definition of a number in, e.g., en_US format. A more lenient way would be to strip the initial '+' from the string, and parse it.

averbraeck commented 1 year ago

Re-generated the code with the new NumberParser class from djutils. The valueOf() funtion now looks as follows:

    public static Area valueOf(final String text)
    {
        Throw.whenNull(text, "Error parsing Area: text to parse is null");
        Throw.when(text.length() == 0, IllegalArgumentException.class, "Error parsing Area: empty text to parse");
        try
        {
            NumberParser numberParser = new NumberParser().lenient().trailing();
            double d = numberParser.parseDouble(text);
            String unitString = text.substring(numberParser.getTrailingPosition()).trim();
            AreaUnit unit = AreaUnit.BASE.getUnitByAbbreviation(unitString);
            if (unit == null)
                throw new IllegalArgumentException("Unit " + unitString + " not found");
            return new Area(d, unit);
        }
        catch (Exception exception)
        {
            throw new IllegalArgumentException(
                    "Error parsing Area from " + text + " using Locale " + Locale.getDefault(Locale.Category.FORMAT),
                    exception);
        }
    }

And all unit tests work fine.