Allow numbers to have either dot or comma as decimal seperator

Theory is always that the decimal separator depends on the locale. While this is generally true, the situation (at least here in Belgium) is not always that simple. We (in this part) speak Dutch which is a language close to English, but also have French speaking citizens. Because of this, the Belgian keyboard is a variant of the French keyboard. In principle the Belgian locale uses a comma as decimal separator, but many numeric keypads produce a dot anyway. To make a long story short, to make sure that everybody can just type a number with fractional part without thinking, both the comma and dot should be allowed as decimal separator.

The application is written using tapestry5 and this framework is wonderfully powerful. It has an embedded IOC engine which allows plugging all components, including the translators which are used.

The only thing which needs to be done to achieve this is replace the double translator. The new version uses the following code.

public class DoubleTranslator implements Translator<Double>
{
    /**
     * Parses blank values to null, otherwise parses the client value to a double
     *
     * @throws ValidationException if the clientValue can not be parsed
     */
    public Double parseClient(String clientValue, Messages messages) throws ValidationException
    {
        if (InternalUtils.isBlank(clientValue))
            return null;

        try
        {
            return new Double(clientValue.replace(',','.').trim());
        }
        catch (NumberFormatException ex)
        {
            throw new ValidationException(messages.format("number-format-exception", clientValue));
        }
    }

    /**
     * Converts null to the blank string, non-null to a string representation.
     */
    public String toClient(Double value)
    {
        return value == null ? "" : value.toString();
    }
}

This then needs to be wired into the system. For this, inside the module class you have to add the following.

public static void contributeTranslatorDefaultSource( MappedConfiguration<Class, Translator> configuration)
{
    configuration.add(Double.class, new DoubleTranslator());
}

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

*