Explain Codes LogoExplain Codes Logo

Limit Decimal Places in Android EditText

java
input-validation
decimal-places
android-edittext
Alex KataevbyAlex Kataev·Nov 28, 2024
TLDR

Enforce a decimal limit in an Android EditText using a custom InputFilter. This concise java code snippet limits user input to up to two decimal places:

editText.setFilters(new InputFilter[] { new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) { if (source.equals(".") && destination.toString().contains(".")) return ""; // eliminate double dots int dotPosition = destination.toString().indexOf("."); if (dotPosition > 0 && destination.length() - dotPosition > 2) return ""; // precision up to two decimal places return null; } } });

The > 2 can be adjusted to fit your desired decimal precision.

A deeper dive: enhancing precision with input validation

Working with finance applications often requires precision, and controlling the number of decimal places in user input is key, as misplacement can lead to significant miscalculations.

Using InputFilter for precision control

Creating a DecimalDigitsInputFilter class acting as an InputFilter helps place exact limitations on the number of decimal places.

public class DecimalDigitsInputFilter implements InputFilter { private Pattern mPattern; public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) { mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?"); // regex: "Don't play by guess, test with a regex!" - true coders' wisdom } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) { Matcher matcher = mPattern.matcher(destination); if (!matcher.matches()) return ""; return null; } }

Apply this filter to the EditText as shown below:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5, 2)});

In-place feedback with TextWatcher

For a more real-time feedback, consider using TextWatcher to monitor and adjust input on-the-fly.

editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { String text = s.toString(); int dotPos = text.indexOf("."); if (dotPos < 0) return; if (text.length() - dotPos - 1 > 2) { s.delete(dotPos + 3, text.length()); // "too many decimal places can make you lose your space" — coders' punchable saying } } });

Achieving better precision in financial applications

Handling monetary amounts and financial management in an app requires stringent control of user input for accuracy.

On-the-fly manipulation using SpannableStringBuilder

With SpannableStringBuilder, you can handle text manipulation effectively without breaking user input rhythm—especially handy when formatting numerical input in real-time.

Limiting numeric inputs

Apart from restricting decimal places, you should also focus on validating other aspects of the input, such as:

  • Limiting the number of digits allowed before the decimal point.
  • Ensuring single decimal point entry.
  • Controlling the precision of the decimal part.

Keep regex simple and maintainable

While regex adds control over user input, simplicity should prevail to avoid unnecessarily complex code maintenance. Always prefer simpler regex that still accomplishes the task.

Streamlining financial input handling

Formatting the user input is crucial for improving user experience in financial applications. Your EditText should guide the user to input data in the right format.

Customizing input control with InputFilter

A robust control of user input can be achieved by using a custom InputFilter. It enables you to set sophisticated restrictions within one filter, rather than applying multiple components to enforce separate rules.

Ensuring valid financial input

By validating user input with a custom filter, common errors due to incorrect decimal usage or entries with more than the required decimal figures can be prevented, thereby ensuring data integrity and trust.

Adherence to financial formatting conventions

It's crucial that your EditText not just restricts user entries to a specific numeric format, but also conforms to the local financial formatting conventions—whether it's the placing of a currency symbol, a decimal separator, or the digit grouping.