0

我有一个语言环境设置为 fr 的 GWT 项目。我有一个自定义文本字段,它使用数字格式来验证和格式化数字输入。

格式化工作正常,但不是输入验证。这是验证新值是否为有效百分比的方法的快照(这称为 onValueChanged):

    private void validateNumber(String newVal){
    logger.debug("value changed, newVal="+newVal+", current="+current);
    // Attempt to parse value
    double val=0;
    try{
        val=Double.parseDouble(newVal);
    }catch(NumberFormatException e){
        logger.warn("parsing failed",e);
        try{
            val=getFormatter().parse(newVal);
        }catch(NumberFormatException ex){
            logger.warn("parsing with nb format failed",ex);
            // on failure: restore previous value
            setValue(current,false);


            return;
        }
    }
      //some check on min and max value here
}

例如,如果程序将起始值设置为“0.2”,它将显示为 20,00 %,因此使用正确的小数分隔符。现在:

  • 如果我输入 0,1 我得到一个数字格式异常。
  • 如果我输入 0.1 它显示为 10,00 %
  • 如果我 10%(在 '%' 之前没有空格),我得到一个 numberformat 异常

您知道如何修改方法以将 0,1 和 10% 识别为有效输入吗?

4

2 回答 2

0

正如 Colin 所提到的,您肯定希望使用 GWT Number Format 对象而不是 Double 来解析和格式化,因此解析和格式化是特定于区域设置的。

下面是一些我可以找到的用于解析、验证和格式化百分比数字的代码片段。

但是请注意,编辑过程在文本框值之外硬编码了 % 单位,因此在编辑过程中没有 20,45% 和 0.2045 之间的转换,直接输入 20,45 并因此可视化。我隐约记得在编辑过程中为这种转换而苦苦挣扎,但因为那是前一阵子而忘记了细节。因此,如果它是您的问题和要求的关键部分,那么恐怕下面的示例可能价值有限。不管怎样,他们来了!

注释:

TextBox txt = new TextBox();
NumberFormat _formatFloat = NumberFormat.getFormat("#,##0.00");
NumberFormat _formatPercent = NumberFormat.getFormat("##0.00%");

将“20,45”之类的文本条目解析为 20.45(而不是“20,45%”为 0.2045):

txt.setText("20,45"); // French locale format example, % symbol hard-coded outside of text box.
try {
  float amount = (float) _formatFloat.parse(txt.getText());
} catch (NumberFormatException e) ...

解析和验证文本条目,如“20,45”:

private class PercentEntryValueChangeHandler implements ValueChangeHandler<String>
{
  @Override
  public void onValueChange(ValueChangeEvent<String> event)
  {
    validatePercent((TextBox) event.getSource());
  }
};

private void validatePercent(final TextBox percentTextBox)
{
  try
  {
    if (!percentTextBox.getText().isEmpty())
    {
      final float val = (float) _formatFloat.parse(percentTextBox.getText());
      if (isValid(val))
        percentTextBox.setText(_formatFloat.format(val));
      else
      {
        percentTextBox.setFocus(true);
        percentTextBox.setText("");
        Window.alert("Please give me a valid value!");
      }
    }
  }
  catch (NumberFormatException e)
  {
    percentTextBox.setFocus(true);
    percentTextBox.setText("");
    Window.alert("Error: entry is not a valid number!");
  }
}

private boolean isValid(float val) { return 12.5 < val && val < 95.5; }

txt.addValueChangeHandler(new PercentEntryValueChangeHandler());

将 20.45 格式化为“20,45”:

float val = 20.45;
txt.setText(_formatFloat.format(val));

将 0.2045 格式化为“20,45%”(只读过程,文本框不可编辑,% 设置在文本框内):

float val = 0.2045;
txt.setText(_formatPercent.format((double)(val))); // * 100 embedded inside format.

它并不花哨,可能远非完美,但它确实有效!任何有关如何改进此实现的反馈都非常受欢迎和赞赏!无论如何,我希望它有所帮助。

于 2013-06-28T16:55:04.293 回答
0

我设法通过将代码更改为以下内容来使其工作:

private void validateNumber(String newVal){
    double val=0;
    try{
        val=getFormatter().parse(newVal);
    }catch(NumberFormatException e){
        boolean ok=false;
        try{
            val=NumberFormat.getDecimalFormat().parse(newVal);
            ok=true;
        }catch(NumberFormatException e1){}
        if(!ok){
            try{
                val=Double.parseDouble(newVal);

            }catch(NumberFormatException ex){
                setValue(current,false);
                // inform user
                Window.alert(Proto2.errors.myTextField_NAN(newVal));
                return;
            }
        }
    }
于 2013-07-13T13:04:47.450 回答