正确的方法来处理NumberFormatException

时间:2013-02-04 09:34:23

标签: java android exception numberformatexception

  

可能重复:
  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) {

            }

        }
    });

感谢

2 个答案:

答案 0 :(得分:2)

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

在你的情况下,只需将try上面的两个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;

答案 1 :(得分:0)

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

NumberFormatException - Android

lang.NumberFormatException in android

相关问题