在GWT中将字符串转换为BigDecimal

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

最简单的方法是创建inheritanceValueBox的新文本框小部件。 如果以这种方式执行,则不必手动转换任何字符串值。 ValueBox负责这一切。

要输入BigDecimal值,您可以去:

BigDecimal value = myTextBox.getValue();

你的BigDecimalBox.java

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

然后你的BigDecimalRenderer.java

 public class BigDecimalRenderer extends AbstractRenderer { private static BigDecimalRenderer INSTANCE; public static Renderer 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 { private static BigDecimalParser INSTANCE; public static Parser 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-Math 。