且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 GWT 中将字符串转换为 BigDecimal

更新时间:2023-02-03 09:25:31

最简单的方法是创建新的继承 ValueBox 的文本框小部件.如果您这样做,您将不必手动转换任何字符串值.ValueBox 负责处理这一切.

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.

要输入 BigDecimal 值,您可以:

To get the BigDecimal value entered you can just go:

BigDecimal value = myTextBox.getValue();

您的 BigDecimalBox.java:

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

然后是您的 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);
  }
}

还有你的 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);
    }
  }
}