-1

可能重复:
如何处理数字格式异常

我想以 $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) {

            }

        }
    });

谢谢

4

2 回答 2

2

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

在您的情况下,只需将尝试放在双 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;
于 2013-02-04T09:41:05.617 回答
0

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

NumberFormatException - Android

lang.NumberFormatException 在 android

于 2013-02-04T09:41:07.370 回答