在 GWT 中将字符串转换为 BigDecimal

2023-12-11

在我的 GWT Web 应用程序中,我有一个包含价格的文本框。 如何将该 String 转换为 BigDecimal?


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

要获取输入的 BigDecimal 值,您可以执行以下操作:

BigDecimal value = myTextBox.getValue();

Your 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);
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 GWT 中将字符串转换为 BigDecimal 的相关文章

随机推荐