Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

BigDecimalFormatter For JFormattedTextfield

DZone's Guide to

BigDecimalFormatter For JFormattedTextfield

·
Free Resource
This BigDecimalFormatter tries to parse the text as BigDecimal for the current locale. It uses the BigDecimal(String) constructor to keep the number of decimals from the text.


public class BigDecimalFormatter extends NumberFormatter {
    public Object stringToValue(String text) throws ParseException {
        if("".equals(text.trim())) {
             return null;
         }
         char ds = getDefaultLocaleDecimalSeparator();

         try {
             String val = text;
             if(ds != '.') {
                 val = val.replace(".", "").replace(ds, '.');
             }
             return new BigDecimal(val);
         } catch(NumberFormatException e) {
             return null;
         }
    }

    public String valueToString(Object value) throws ParseException {
        return super.valueToString(value);
    }

    private char getDefaultLocaleDecimalSeparator() {
          DecimalFormatSymbols symbols = new DecimalFormat("0").getDecimalFormatSymbols();
          char ds = symbols.getDecimalSeparator();
          return ds;
      }

}



public class BigDecimalFormatterFactory extends JFormattedTextField.AbstractFormatterFactory {
    public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
        return new BigDecimalFormatter();
    }
}


Use it like this:


bigdecimalfield.setFormatterFactory(new BigDecimalFormatterFactory());
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}