Can you make a TextField accept both , and . as decimal separator?

后端 未结 1 413
余生分开走
余生分开走 2021-01-12 13:08

In a Wicket app, I have a decimal number text field:

 TextField f = 
     new TextField(\"f\", new PropertyModel

        
相关标签:
1条回答
  • 2021-01-12 13:52

    Thanks to @bert's comment, and the Wicket in Action book, I found an approach that works. In the Application class specify a custom converter for BigDecimals:

    @Override
    protected IConverterLocator newConverterLocator() {
        ConverterLocator converterLocator = new ConverterLocator();
        converterLocator.set(BigDecimal.class, new CustomBigDecimalConverter());
        return converterLocator;
    }
    

    And in the custom converter, convertToObject needs to be overridden. NB: this is sufficient for our needs; think about your requirements and adapt as needed!

    public class CustomBigDecimalConverter extends BigDecimalConverter {
    
        @Override
        public BigDecimal convertToObject(String value, Locale locale) {
            // NB: this isn't universal & your mileage problably varies!
            // (Specifically, this breaks if '.' is used as thousands separator)
            if ("fi".equals(locale.getLanguage())) {
                value = value.replace('.', ',');
            }
            return super.convertToObject(value, locale);
        }
    }
    

    Edit: Offtopic, but I want to document this too. We needed our app to support a scale of 4 decimal places, and our custom BigDecimal converter nicely solves that problem too.

      @Override
        public String convertToString(Object value, Locale locale) {
            NumberFormat fmt = getNumberFormat(locale);
            fmt.setMaximumFractionDigits(4); // By default this is 3.
            return fmt.format(value);
        }
    

    After this customisation, a decimal number like 2.0005 will be shown as 2.0005 instead of 2.

    0 讨论(0)
提交回复
热议问题