Android EditText listening allows users to enter only two decimal places, androidedittext
Recently, you need to enter the price, but you do not want to input too many values after the decimal point, so I encapsulated one. When the user inputs the decimal point, the number of digits after the decimal point is monitored. If the number is greater than two digits, it is immediately deleted. It is encapsulated and can be used directly!
public static void setPricePoint(final EditText editText) {editText.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {if (s.toString().contains(".")) {if (s.length() - 1 - s.toString().indexOf(".") > 2) {s = s.toString().subSequence(0,s.toString().indexOf(".") + 3);editText.setText(s);editText.setSelection(s.length());}}if (s.toString().trim().substring(0).equals(".")) {s = "0" + s;editText.setText(s);editText.setSelection(2);}if (s.toString().startsWith("0")&& s.toString().trim().length() > 1) {if (!s.toString().substring(1, 2).equals(".")) {editText.setText(s.subSequence(0, 1));editText.setSelection(1);return;}}}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {}@Overridepublic void afterTextChanged(Editable s) {// TODO Auto-generated method stub}});}
In the android EditText control, how to judge and limit that only numbers can be entered
Use the android: numeric = "decimal" attribute for Decimals
Then, convert the data type after gettext.
There are actually many solutions.
You can add a TextChangedListener listener for character judgment.
Android: digits attribute input rules
For example, android: digits = "0123456789" indicates that only numbers are allowed.
Android: digits = "0123456789." indicates that the number and decimal point can be entered.
C # How can I input only two digits after the decimal point in textbox?
Use the value. tostring ("2F") to keep two decimal places before assigning values to textbox.