问题
I am using an EditText to allow a user to input a value that is stored in a Double.
However, by default, Doubles look like "0.0" and it's a little annoying for a user to backspace over the extra decimal if it's not used. Is there a way to force-display whole numbers to look like "0" and only show the decimal if the user actually decides to use it?
Current code:
myEditText = (EditText) view.findViewById(R.id.my_edittext);
myEditText.setText(myVariable + "");
myEditText.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 temp = s.toString();
if (s.length() > 0){
if (OtherMethods.isDouble(temp)) {
myVariable = Double.parseDouble(temp);
}
else {
myVariable = 0.0;
}
}
else {
myVariable = 0.0;
}
}
});
The XML:
<EditText
android:id="@+id/my_edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:hint="Input Value"
android:imeOptions="actionDone"/>
回答1:
To achieve this you can use NumberFormat
EditText yourEditText = (EditText) findViewById(R.id.editTextID);
//dummy data, will have user's value
double aDouble = 4.0;
//formats to show decimal
NumberFormat formatter = new DecimalFormat("#0");
//this will show "4"
yourEditText.setText(formatter.format(aDouble));
Make sure to validate the user's input. Also, this will only modify what is displayed and not the value itself.
回答2:
Parsing Double to String, then String to Int:
String stringparsed = YourDouble + ""; int intparsed = Integer.parseInt(stringparsed);
Using substring to cut the string from a startIndex to finalIndex:
String stringparsed = YourDouble + ""; String final = stringparsed.substring(0,1); //for example, if the double was 0.0, the result is 0
来源:https://stackoverflow.com/questions/41657200/how-to-default-an-edittext-to-integer-but-allow-decimal-input