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"/>
To achieve this you can use
NumberFormat
Make sure to validate the user's input. Also, this will only modify what is displayed and not the value itself.
Parsing Double to String, then String to Int:
Using substring to cut the string from a startIndex to finalIndex: