在 GWT 中将字符串转换为 BigDecimal [英] Converting String to BigDecimal in GWT

查看:51
本文介绍了在 GWT 中将字符串转换为 BigDecimal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

最简单的方法是创建新的继承 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);
    }
  }
}

这篇关于在 GWT 中将字符串转换为 BigDecimal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆