Search code examples
javagwtbigdecimal

Converting String to BigDecimal in GWT


In my GWT web application I have a textbox that holds a price. How can one convert that String to a BigDecimal?


Solution

  • The easiest way is to create new text box widget that inherits ValueBox. If you do it this way, you won't have to convert any string values manually. the ValueBox takes care of it all.

    To get the BigDecimal value entered you can just go:

    BigDecimal value = myTextBox.getValue();

    Your BigDecimalBox.java:

    public class BigDecimalBox extends ValueBox<BigDecimal> {
      public BigDecimalBox() {
        super(Document.get().createTextInputElement(), BigDecimalRenderer.instance(),
            BigDecimalParser.instance());
      }
    }
    

    Then your BigDecimalRenderer.java

    public class BigDecimalRenderer extends AbstractRenderer<BigDecimal> {
      private static BigDecimalRenderer INSTANCE;
    
      public static Renderer<BigDecimal> instance() {
        if (INSTANCE == null) {
          INSTANCE = new BigDecimalRenderer();
        }
        return INSTANCE;
      }
    
      protected BigDecimalRenderer() {
      }
    
      public String render(BigDecimal object) {
        if (null == object) {
          return "";
        }
    
        return NumberFormat.getDecimalFormat().format(object);
      }
    }
    

    And your BigDecimalParser.java

    package com.google.gwt.text.client;
    
    import com.google.gwt.i18n.client.NumberFormat;
    import com.google.gwt.text.shared.Parser;
    
    import java.text.ParseException;
    
    public class BigDecimalParser implements Parser<BigDecimal> {
    
      private static BigDecimalParser INSTANCE;
    
      public static Parser<BigDecimal> instance() {
        if (INSTANCE == null) {
          INSTANCE = new BigDecimalParser();
        }
        return INSTANCE;
      }
    
      protected BigDecimalParser() {
      }
    
      public BigDecimal parse(CharSequence object) throws ParseException {
        if ("".equals(object.toString())) {
          return null;
        }
    
        try {
          return new BigDecimal(object.toString());
        } catch (NumberFormatException e) {
          throw new ParseException(e.getMessage(), 0);
        }
      }
    }