Reputation: 2259
I have an Android EditText which when a user puts a number, it edits the number and adds thousand separators using Decimal Format, but when one is inputting floating point numbers, i does not add zeros after the decimal point. so i can not input 1.000000008 because the zeros won't go on but other numbers do. Is there any java DecimalFormat pattern that will allow a user to input a zero after the decimal point? Here's the code for my EditText.
am = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
public void afterTextChanged(Editable s) {
amount.removeTextChangedListener(this);
amount2.setText(s.toString());
try {
int inilen, endlen;
inilen = amount.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
value = Double.parseDouble(v);
int cp = amount.getSelectionStart();
if (hasFractionalPart) {
amount.setText(df.format(n));
} else {
amount.setText(dfnd.format(n));
}
endlen = amount.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= amount.getText().length()) {
amount.setSelection(sel);
} else {
// place cursor at the end?
amount.setSelection(amount.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
amount.addTextChangedListener(this);
}
};
Upvotes: 1
Views: 1627
Reputation: 86948
Rewrite
First, when a decimal symbol is present let's count how many zeros will be trimmed off by the formatter. (If we find a non-zero character after the decimal, we'll reset our count. For example 1.00200
only has two trailing zeros.) In onTextChanged()
:
int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
trailingZeroCount = 0;
if (index > -1)
{
for (index++; index < s.length(); index++) {
if (s.charAt(index) == '0')
trailingZeroCount++;
else {
trailingZeroCount = 0;
}
}
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
Next, append the appropriate number of zero's back on to the formatted String. In afterTextChanged()
:
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
amount.setText(df.format(n) + trailingZeros.toString());
} else {
amount.setText(dfnd.format(n));
}
Note: You haven't posted the formats you use, so I've had to make a few assumptions, but this is easily adaptable.
Upvotes: 1