可能重复:
如何处理数字格式异常
我想以 $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) {
}
}
});
谢谢