DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

BigDecimalFormatter For JFormattedTextfield

  • submit to reddit
        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());