Do you know any method so that users can enter numbers with the maximum number of decimal places. I am not sure how to solve this problem. In an MS SQL database, I am going to send data from my application. I have columns with this decimal(8,3) type decimal(8,3) Now, looking at the data type of the column that will finally store the value I want to test on Android, I looked at these two cases:
- If the user enters a number without decimals, the maximum number of digits must be 8
- If the user enters a decimal number, the maximum number of digits must be 8 (including the digits to the right of the decimal point)
Now I'm sure in the first case, but not so much about the second. Is it correct to fix the number of maximum digits (for example, always 8)? Or should I consider entering a maximum of 8 digits to the left and 3 to the right of the decimal point?
Anyway, this is what I tried on Android:
mQuantityEditText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { String str = mQuantityEditText.getText().toString(); DecimalFormat format = (DecimalFormat) DecimalFormat .getInstance(); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); char sep = symbols.getDecimalSeparator(); int indexOFdec = str.indexOf(sep); if (indexOFdec >= 0) { if (str.substring(indexOFdec, str.length() - 1).length() > 3) { s.replace(0, s.length(), str.substring(0, str.length() - 1)); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } });
Although the code above handles the maximum number of decimal places. It does not limit the total number of digits allowed in EditText.
Do you think you could help me improve my code so that it processes both the maximum number of decimal places and the total number of digits allowed in EditText (given both numbers to the left and right of the decimal point)
EDIT
Ok, now I'm trying to suggest Joรฃo Sousa and this is what I tried:
1) I defined a class that implements InputFilter
public class NumberInputFilter implements InputFilter { private Pattern mPattern; public NumberInputFilter(int precision, int scale) { String pattern="^\\-?(\\d{0," + (precision-scale) + "}|\\d{0," + (precision-scale) + "}\\.\\d{0," + scale + "})$"; this.mPattern=Pattern.compile(pattern); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) { if (end > start) {
2) Tried to use the class as follows:
mQuantityEditText.setFilters(new InputFilter[] { new NumberInputFilter(8,3)} );