Possible Duplicate:
how to handle number format exception
i want to enter digit in format like $22,000,420 everything is fine but when i erase number it shows number formatting exception.
my xml file is as follows:-
<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" />
and my android java code is as follows:-
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) {
}
}
});
thanks
Please search for similar questions before posting a question, Take a look here:Similar Question
in your case just put the try above double s1 =, like this
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;