【问题标题】:Correct way to handle NumberFormatException [duplicate]处理 NumberFormatException 的正确方法 [重复]
【发布时间】:2013-02-04 09:34:22
【问题描述】:

可能重复:
how to handle number format exception

我想以 $22,000,420 之类的格式输入数字,一切都很好,但是当我删除数字时,它显示数字格式异常。

我的xml文件如下:-

<EditText
        android:id="@+id/editAmountFinanced"
        style="@style/EditTextInputFinance"
        android:layout_below="@+id/txtCreateNewAccount"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="AMOUNT FINANCED"
         android:digits="0123456789.,$"
        android:padding="10dp" />

而我的android java代码如下:-

 editAmountFinanced = (EditText)findViewById(R.id.editAmountFinanced);

 editAmountFinanced.addTextChangedListener(new TextWatcher() {

        boolean isEdiging;
        @Override
        public void onTextChanged(CharSequence s, int start, int before,  int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            if(isEdiging) return;
            isEdiging = true;

            String str = s.toString().replaceAll( "[^\\d]", "" );
            double s1 = Double.parseDouble(str);

            NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
            ((DecimalFormat)nf2).applyPattern("$ ###,###.###");
            try {

                s.replace(0, s.length(), nf2.format(s1));

                isEdiging = false;
            } catch(NumberFormatException e) {

            }

        }
    });

谢谢

【问题讨论】:

    标签: java android exception numberformatexception


    【解决方案1】:

    请在发布问题之前搜索类似的问题, 看这里:Similar Question

    在你的情况下,只需将 try 放在 double s1 = 之上,就像这样

        double s1 = 0.0;
          try {
               s1 = Double.parseDouble(str);
         } catch(NumberFormatException e) {}
            NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
            ((DecimalFormat)nf2).applyPattern("$ ###,###.###");
             s.replace(0, s.length(), nf2.format(s1));
    
             isEdiging = false;
    

    【讨论】:

    • 你能解释一下到底发生了什么吗?
    • 但是随着 try 和 catch 在 Double.parseDouble 中移动,异常应该被捕获......所以这应该不是问题
    • ya 然后我没有收到任何错误,但我想输入 $ 符号和逗号
    • 将上述代码添加到您的 catch 线索将解决问题
    • 刚刚编辑了答案,并在我的设备上进行了测试,工作 100%
    【解决方案2】:

    我想你会从下面的问题和答案中得到答案

    NumberFormatException - Android

    lang.NumberFormatException in android

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2010-12-08
      • 2011-02-28
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多