user2980156
user2980156

Reputation: 59

How to make an edittext both signed and decimal?

is there a way to change edittext settings to both decimal (3.4) and singed(+/-)? and what tipe of variable should i set in my activity? I tried with decimal, number and signed but i want to use a number like -3.6 and to store it in my activity.

Upvotes: 4

Views: 1722

Answers (1)

Michael Yaworski
Michael Yaworski

Reputation: 13483

In your activity class:

EditText editText = (EditText)findViewById(R.id.editText);
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL);

from InputType | Android Developers

__________________________________________________________________________________

OR:

In your activity class:

EditText editText = (EditText)findViewById(R.id.editText);
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789.-"));

That allows the EditText to input decimals and negative signs, as you can see at the end of the line.

__________________________________________________________________________________

OR:

In your EditText XML properties, add this property:

android:inputType="numberSigned|numberDecimal"

__________________________________________________________________________________

You can input the number to a String to store the value inputted:

EditText editText = (EditText)findViewById(R.id.editText);
String userInput = editText.getText().toString();

userInput will then be equal to the String that the user inputted. To convert it to a double, you can do this:

// however, this will break your app if you convert an empty String to a double
// so if there could be no text in the EditText, use a try-catch
double userInputDouble = Double.parseDouble(editText.getText().toString());

Upvotes: 4

Related Questions