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
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.
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
Related
What I have:
I have an EditText which accepts decimal input and I setted the default value in the XML to 0.00 (if there is no input yet)
If the user press 1, then the value change to 1. If he needs to enter decimal value then he must press the dot . on the keyboard.
What I want:
I want to auto format the EditText in a decimal format 0.00, so if a user press 1 if becomes 0.01 instead of 1 (Like in the PAYPAL App). If he entered 100, then the value in the EditText must be formatted as 1.00.
I know this can be done by using TextWatcher but I don't know how to achieve this.
End Result Comparison:
WHAT I HAVE
1 = 1
11 = 11
222 = 222
WHAT I NEED
1 = 0.01
11 = 0.11
222 = 2.22
UPDATE:
My actual TextWatcher looks like below just to set the default value to 0.00 if the user deletes all inputs (to prevent error on calculated functions).
private class EditTextListener implements 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) {
if (editText.getText().toString().equals("") || editText.length() < 1){
editText.setText("0.00");
editText.post(() -> editText.setSelection(editText.getText().length()));
} else {
BigDecimal amount = new BigDecimal(editText.getText().toString());
}
}
}
as you described you need to divide it by 100 with decimal points:
#Override
public void afterTextChanged(Editable s) {
if (editText.getText().toString().equals("") || editText.length() < 1) {
editText.setText("0.00");
editText.post(() -> editText.setSelection(editText.getText().length()));
} else {
double amount = Double.parseDouble(editText.getText().toString());
editText.setText(String.format("%.2f", (amount / 100.0));
}
}
Try use this code
edtQtdVolume.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) {
edtQtdVolume.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[R$,.]", "");
double parsed = Double.parseDouble(cleanString);
Locale locale = new Locale("en", "US");
NumberFormat nf = NumberFormat.getNumberInstance(locale);
DecimalFormat formatter = (DecimalFormat) nf;
formatter.applyPattern("#0.00");
String formatted = formatter.format((parsed/100));
edtQtdVolume.setText(formatted);
edtQtdVolume.setSelection(formatted.length());
edtQtdVolume.addTextChangedListener(this);
lista.get(position).setQtdVolumeInformadoColeta(Double.valueOf(formatted));
}
#Override
public void afterTextChanged(Editable s) {
}
});
I am new to Java /android studio, need help with this-
I have a TextinputEditText field- accountEt (one can input number to this field)
I need to calculate and display- accountEt * ((100-3) / 100);
[Basically, if 100 entered it shows 97, if 10 entered it shows 9.7]
How to do this in android studio? > show the result (9.7) in a TextView properly.
Like-
Textfield accountEt- [10] | (edit text) Result-
[9.7] |(text view)
Any help is useful.
If you use a button to calculate the result. In your button onclick listener just save the value of text value to string and calculate the resut using the value and store it another variable. And finally set the result to your edittext
int a=Integer.parseInt(edittextname.gettext().tostring());
float result=a * ((100-3) / 100);
accountet.settext(Float.toString(result));
Get edit Text value in String.
calculate the result and store in the String Data Type.
Show on String value on the Text View.
String calculate=accountEt.getText.ToString();
String newCalcualatedValue=calculate.toInt* ((100-3) / 100);
textView.setText(newCalcualatedValue);
If you want to update the text automatically on text input, do this:
accountEt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
String text = editText.getText().toString();
int num;
if (text.isEmpty())
num = 0;
else
num = Integer.parseInt(editText.getText().toString());
double res = num * 0.97;
result.setText(Double.toString(res));
}
});
I'm trying to create a simple calculator that is automatic - no more equal sign. Here's how it should go:
1. User inputs the first number.
2. User chooses an operation "add", "subtract" etc.
3. User inputs the second number. In this stage, the program should now automatically compute the answer. For example:
user inputs "2" as the first number;
user chooses "add";
user inputs "3" (second number this time)
it should then display "5" in the result box.
if the user continues to input "2", this means the second number is now "32" instead of "3", and the result will be "34"
Here's my code:
public String int_firstnumber = "";
public String int_secondnumber = "";
public int int_result = 0;
public int int_numberone = 0;
public int int_numbertwo = 0;
public String str_operation = "";
public String str_inputdisplay = "";
public String str_indicator = "none";
public String str_focus = "first";
// BUTTON 1
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checks the indicator
if(str_focus=="first") {
int_firstnumber = int_firstnumber +"1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
} else {
if(str_indicator=="add"){
int_secondnumber = int_secondnumber + "1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
int_numberone = Integer.parseInt(int_firstnumber);
int_numbertwo = Integer.parseInt(int_secondnumber);
int_result = int_numberone + int_numbertwo;
lblresult.setText(int_result);
}
}
}
});
//END OF BUTTON 1
//BUTTON ADD
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
str_indicator = "add";
str_operation = " + ";
str_focus = "second";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
}
});
This somewhat works but not completely. If I Input "1", it'll display 1 on the str_inputdisplay, I then click the + symbol or the btnadd, it then displays 1+ in the str_inputdisplay. This means that we are on the second number right? However when I input 1 again, the app just force closes.
Any ideas why this is happening? Forgive my ways of code, I just started learning Java btw. Thanks!
why are you naming your variable 'int_firstnumber' when it's a string public String int_firstnumber when all your other variables are named according to the variable type like int int_result and str_operation
your code looks a bit more complicated then it needs to be. as someone mentioned you can't add two numbers when your operator is a string i.e. string operator = "+"; it won't get treated like an operand, it will get treated for the type it is which is a string.
why not if they select "first" call a method setFirstNumber that way you can validate input and set the first number.. something like this:
public void setFirstNumber(int firstNumber){
int_numberone = firstNumber;
}
and then when "add" gets selected call a second method setSecondNumber along with an addition method
public void setSecondNumber(int secondNumber){
int_numbertwo = secondNumber;'
}
and
public int addNumbers(int firstNumber, int secondNumber){
return firstNumber + secondNumber;
}
your result will be int_result = addNumbers(int_numberOne, int_numberTwo)
this way your code is much cleaner, each function is executing one task, and if you want to add additional operations later it's easy to add a function subtract, multiply, etc
public int subtractNumbers(int firstNumber, int secondNumber){
return firstNumber - secondNumber;
}
public int multiplyNumbers(int firstNumber, int secondNumber){
return firstNumber * secondNumber;
}
hope that helps!
You should add TextWatcher to the input fields. You will get the values in callbaks there which you can use to update the view showing answer.
Two issues:
When adding two strings, addition will not happen. Change it to int, long etc when you want to do operation like:
int_firstnumber = int_firstnumber +"1";
Hopefully you are properly setting the variables str_focus and str_indicator because that is not available in the code snippet you have given.
if("first".equals(str_focus)) {
......
int_firstnumber = int_firstnumber +1;
} else {
if("add".equals(str_indicator)){
......
int_secondnumber = int_secondnumber + 1;
so I believe I am overthinking this but I want to double check.
I am getting my TextView from my EditText widget.
addMileage.setOnClickListener(new OnClickListener() {
#Override
public void OnClick(View v) {
if (isErase) {
nextMileage.setText(mileageInput.getText().toString());
} else {
nextMileage.setText("");
}
isErase = !isErase;
}
How can I take what the user enters in the EditText then automatically take the number entered and + 3500. Then display in TextView?
int result=Integer.parseInt(mileageInput.getText().toString())+3500;
nextMileage.setText(result+"");
You can do like this
onClick
String s = your_editText.getText().toString();
if (!s.trim().equals("")
{
int i = Integer.parseInt(s);
int sum = i + 3500;
your_textView.setText(" " + sum);
}
else
your_textView.setText("Please enter the number");
Assuming the code you have works (you didn't say it doesn't work), you can edit the if body as
if (isErase) {
String mileageStr = (Integer.parseInt(mileageInput.getText().toString()) + 3500) + "";
nextMileage.setText(mileageStr);
}
Integer.parseInt() allows you to convert a string to an integer quickly.
All-
I have a TextWatcher that formats an EditText to currency format:
private String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
editText$.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formated;
editText$.setText(formated);
editText$.setSelection(formated.length());
editText$.addTextChangedListener(this);
}
}
This works great, the problem is that my EditText only needs whole numbers so I do not the user to be able to enter cents. So instead of 0.01 than 0.12 than 1.23 than 12.34, I want 1 than 12 than 123 than 1,234. How can I get rid of the decimal point but keep the commas? Thank you.
If you don't mind removing the period and trailing zeroes, you could do this:
mEditText.addTextChangedListener(new TextWatcher() {
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
annualIncomeEntry.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,]", "");
if (cleanString.length() > 0) {
double parsed = Double.parseDouble(cleanString);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(0);
current = formatter.format(parsed);
} else {
current = cleanString;
}
annualIncomeEntry.setText(current);
annualIncomeEntry.setSelection(current.length());
annualIncomeEntry.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
This will set the number formatter's maximum fraction digits to zero, removing all trailing zeroes and the period. I also removed the division by 100 so that all entered numbers are integers.
Also make sure that your EditText's inputType is "number" or this will crash if the user tries to enter a non-numeric character.
Hexar's answer was useful but it lacked error detection when the user deleted all the numbers or moved the cursor. I built on to his answer and an answer here to form a complete solution. It may not be best practice due to setting the EditText in the onTextChanged() method but it works.
/* don't allow user to move cursor while entering price */
mEditText.setMovementMethod(null);
mEditText.addTextChangedListener(new TextWatcher() {
private String current = "";
NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double parsed;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
/* remove listener to prevent stack overflow from infinite loop */
mEditText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,]", "");
try {
parsed = Double.parseDouble(cleanString);
}
catch(java.lang.NumberFormatException e) {
parsed = 0;
}
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format(parsed);
current = formatted;
mEditText.setText(formatted);
/* add listener back */
mEditText.addTextChangedListener(this);
/* print a toast when limit is reached... see xml below.
* this is for 6 chars */
if (start == 7) {
Toast toast = Toast.makeText(getApplicationContext(),
"Maximum Limit Reached", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
A quick way to ensure the user doesn't enter invalid information is to edit the xml. For my program, a limit of 6 number characters was set.
<!-- it says maxLength 8 but it's really 6 digits and a '$' and a ',' -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|textVisiblePassword"
android:maxLength="8"
android:digits="0123456789"
android:id="#+id/mEditText"
android:hint="Price"/>
Why don't you format the amount using currencyFormat and then take out the .00 from the String.
private static final ThreadLocal<NumberFormat> currencyFormat = new ThreadLocal<NumberFormat>() {
#Override
protected NumberFormat initialValue() {
return NumberFormat.getCurrencyInstance();
}
};
currencyFormat.get().format( < your_amount_here > )
etProductCost.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) {
if (s.toString().length() == 1){
//first number inserted.
if (s.toString().equals(getString(R.string.currency_symbol))){
//if it is a currecy symbol
etProductCost.setText("");
}else {
etProductCost.setText(getString(R.string.currency_symbol) + s.toString());
etProductCost.setSelection(s.toString().length());
}
return;
}
//set cursor position to last in edittext
etProductCost.setSelection(s.toString().length());
}
#Override
public void afterTextChanged(Editable s) {}
});