Android edit text decimal format - android

Can I ask how to format string value e.g. 5000000.00 to 5,000,000.00? Apparently I'm doing currency related stuff for android application, I can managed to just format string value 5000000 to 5,000,000 without the dot separator in the edit text. I would like to store the string value for later to be used to parseDouble so that I will need to calculate and have some decimals. I managed to do with just comma separator but any idea on how to make the dot to be shown in the edit text as well?
The following is my code:
amountText.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) {
amountText.removeTextChangedListener(this);
if(!amountText.getText().toString().equals(""))
{
try {
String editText = amountText.getText().toString();
String newStr = editText.replace("$", "").replace(",", "");
customer.getProperty().get(groupPosition).setAmount(newStr);
String formattedString = formatString(customer.getProperty().get(groupPosition).getAmount());
amountText.setText(formattedString);
amountText.setSelection(amountText.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
amountText.addTextChangedListener(this);
}
});
public String formatString(String s)
{
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
return formattedString;
}
I have tested use parseDouble but when I input "." in EditText, it just won't appear, and if I used long variable instead, it will give wrong format and error. (java.lang.NumberFormatException: Invalid long: "500000.00"). All values are done in string and later processing I will just parse the value when doing calculation.
Thank you and appreciate for anyone guidance and I apologize if there exists the post that is similar as I did not manage to find solution yet.

This is working & fully tested code just copy & paste it to try
TextWatcher amountTextWatcher = 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) {
int cursorPosition = etAmount.getSelectionEnd();
String originalStr = etAmount.getText().toString();
//To restrict only two digits after decimal place
etAmount.setFilters(new InputFilter[]{new MoneyValueFilter(Integer.parseInt(2))});
try {
etAmount.removeTextChangedListener(this);
String value = etAmount.getText().toString();
if (value != null && !value.equals("")) {
if (value.startsWith(".")) {
etAmount.setText("0.");
}
if (value.startsWith("0") && !value.startsWith("0.")) {
etAmount.setText("");
}
String str = etAmount.getText().toString().replaceAll(",", "");
if (!value.equals(""))
etAmount.setText(getDecimalFormattedString(str));
int diff = etAmount.getText().toString().length() - originalStr.length();
etAmount.setSelection(cursorPosition + diff);
}
etAmount.addTextChangedListener(this);
} catch (Exception ex) {
ex.printStackTrace();
etAmount.addTextChangedListener(this);
}
}
}
};
etAmount.addTextChangedListener(amountTextWatcher);
Here is method to add comma seperator to decimal number
/**
* Get decimal formated string to include comma seperator to decimal number
*
* #param value
* #return
*/
public static String getDecimalFormattedString(String value) {
if (value != null && !value.equalsIgnoreCase("")) {
StringTokenizer lst = new StringTokenizer(value, ".");
String str1 = value;
String str2 = "";
if (lst.countTokens() > 1) {
str1 = lst.nextToken();
str2 = lst.nextToken();
}
String str3 = "";
int i = 0;
int j = -1 + str1.length();
if (str1.charAt(-1 + str1.length()) == '.') {
j--;
str3 = ".";
}
for (int k = j; ; k--) {
if (k < 0) {
if (str2.length() > 0)
str3 = str3 + "." + str2;
return str3;
}
if (i == 3) {
str3 = "," + str3;
i = 0;
}
str3 = str1.charAt(k) + str3;
i++;
}
}
return "";
}
Method to restrict only two digits after decimal place in edittext
/**
* Restrict digits after decimal point value as per currency
*/
class MoneyValueFilter extends DigitsKeyListener {
private int digits;
public MoneyValueFilter(int i) {
super(false, true);
digits = i;
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharSequence out = super.filter(source, start, end, dest, dstart, dend);
// if changed, replace the source
if (out != null) {
source = out;
start = 0;
end = out.length();
}
int len = end - start;
// if deleting, source is empty
// and deleting can't break anything
if (len == 0) {
return source;
}
int dlen = dest.length();
// Find the position of the decimal .
for (int i = 0; i < dstart; i++) {
if (dest.charAt(i) == '.') {
// being here means, that a number has
// been inserted after the dot
// check if the amount of digits is right
return getDecimalFormattedString((dlen - (i + 1) + len > digits) ? "" : String.valueOf(new SpannableStringBuilder(source, start, end)));
}
}
for (int i = start; i < end; ++i) {
if (source.charAt(i) == '.') {
// being here means, dot has been inserted
// check if the amount of digits is right
if ((dlen - dend) + (end - (i + 1)) > digits)
return "";
else
break; // return new SpannableStringBuilder(source,
// start, end);
}
}
// if the dot is after the inserted part,
// nothing can break
return getDecimalFormattedString(String.valueOf(new SpannableStringBuilder(source, start, end)));
}
}

Try this:
public void afterTextChanged(Editable view) {
String s = null;
try {
// The comma in the format specifier does the trick
s = String.format("%,d", Long.parseLong(view.toString()));
} catch (NumberFormatException e) {
}
// Set s back to the view after temporarily removing the text change listener
}
Source: How to Automatically add thousand separators as number is input in EditText

Related

How to add thousand separator in android EditText .........?

I want to separate automatically edit text like (9,99,999) like this. i searched for this on web but i am not getting proper solution for this.
can you please help me.thank you stack overflow.
You can use DecimalFormat for this like below Code:
public String formatNumber(double d) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
formatter.applyPattern("#,###");
return formatter.format(d);
}
You Can Pass Pattern as you want.
public static String formatCurrency(String number) {
try {
number = NumberFormat.getNumberInstance(Locale.US).format(Double.valueOf(number));
} catch (Exception e) {
}
return number;
}
This is what i did. Works perfectly
Try this.
public class NumberTextWatcherForThousand implements TextWatcher {
EditText editText;
public NumberTextWatcherForThousand(EditText editText) {
this.editText = editText;
}
#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) {
try
{
editText.removeTextChangedListener(this);
String value = editText.getText().toString();
if (value != null && !value.equals(""))
{
if(value.startsWith(".")){ //adds "0." when only "." is pressed on begining of writting
editText.setText("0.");
}
if(value.startsWith("0") && !value.startsWith("0.")){
editText.setText(""); //Prevents "0" while starting but not "0."
}
String str = editText.getText().toString().replaceAll(",", "");
if (!value.equals(""))
editText.setText(getDecimalFormat(str));
editText.setSelection(editText.getText().toString().length());
}
editText.addTextChangedListener(this);
return;
}
catch (Exception ex)
{
ex.printStackTrace();
editText.addTextChangedListener(this);
}
}
public static String getDecimalFormat(String value)
{
StringTokenizer lst = new StringTokenizer(value, ".");
String str1 = value;
String str2 = "";
if (lst.countTokens() > 1)
{
str1 = lst.nextToken();
str2 = lst.nextToken();
}
String str3 = "";
int i = 0;
int j = -1 + str1.length();
if (str1.charAt( -1 + str1.length()) == '.')
{
j--;
str3 = ".";
}
for (int k = j;; k--)
{
if (k < 0)
{
if (str2.length() > 0)
str3 = str3 + "." + str2;
return str3;
}
if (i == 3)
{
str3 = "," + str3;
i = 0;
}
str3 = str1.charAt(k) + str3;
i++;
}
}
//Trims all the comma of the string and returns
public static String trimCommaOfString(String string) {
if(string.contains(",")){
return string.replace(",","");}
else {
return string;
}
}
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
editText.removeTextChangedListener(this);
try {
StringBuilder originalString = new StringBuilder(editable.toString().replaceAll(",", ""));
int indx = 0;
for (int i = originalString.length(); i > 0; i--) {
if (indx % 3 == 0 && indx > 0)
originalString = originalString.insert(i, ",");
indx++;
}
editText.setText(originalString);
editText.setSelection(originalString.length());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
editText.addTextChangedListener(this);
}
});

limit edit text in android with decimal

I have a question about limit number in editText. I want to user can enter only number from 1-70. When user want to put 70.01 or more I want to not allowed them.with only two decimal allowed.total length is 5 character including point.
i am able to limit before & after decimal. & also limit the 70 but user can able to enter 70.99(don't know why) in edit text that i want to block. my validation work when user enter 71 or more
this is constructor i im using in fragment
txtno.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(Integer.parseInt(getString(R.string.length)),2,txtno)});
this is for after & before decimal
#Override
public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {
mTextView.setKeyListener(DigitsKeyListener.getInstance(true,true));
String etText = mTextView.getText().toString();
String temp = mTextView.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > mMyint) {
return "";
}
} else {
int dotPosition;
int cursorPositon = mTextView.getSelectionStart();
if (etText.indexOf(".") == -1) {
dotPosition = temp.indexOf(".");
} else {
dotPosition = etText.indexOf(".");
}
if (cursorPositon <= dotPosition) {
String beforeDot = etText.substring(0, dotPosition);
if (beforeDot.length() < mMyint) {
return source;
} else {
if (source.toString().equalsIgnoreCase(".")) {
return source;
} else {
return "";
}
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > mMydec) {
return "";
}
}
}
return null;
}
& this is textWatcher for limit 70
public void afterTextChanged(Editable s) {
try{
if(Integer.parseInt(s.toString())>70){
s.replace(0, s.length(), s.toString());
}
}catch(Exception e){}
Thanks in advance.
the problem is that you try to parse int - you need to parse double.

Limiting a user to enter 1 decimal value in Edit Text

The requirement is to limit user from not entering more than 1 decimal value in a numeric/decimal edit text field. That said, I also need to limit the number entry to 6 Max digits. eg. 999999.9
If a user enters numeric alone - then I should be able to limit the user to 6 digits Max, but should allow "." and decimal number(if entered by the user).
I am not sure, how to do this. Any help and reference will be of great help.
Maybe some implementation similar to this? I'm pretty sure it can be optimized a lot!
EditText et;
.....
// force number input type on edittext
et.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
et.addTextChangedListener(new CustomTextWatcher(et));
where:
class CustomTextWatcher implements TextWatcher {
private NumberFormat nf = NumberFormat.getNumberInstance();
private EditText et;
private String tmp = "";
private int moveCaretTo;
private static final int INTEGER_CONSTRAINT = 6;
private static final int FRACTION_CONSTRAINT = 1;
private static final int MAX_LENGTH = INTEGER_CONSTRAINT + FRACTION_CONSTRAINT + 1;
public CustomTextWatcher(EditText et) {
this.et = et;
nf.setMaximumIntegerDigits(INTEGER_CONSTRAINT);
nf.setMaximumFractionDigits(FRACTION_CONSTRAINT);
nf.setGroupingUsed(false);
}
public int countOccurrences(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this); // remove to prevent stackoverflow
String ss = s.toString();
int len = ss.length();
int dots = countOccurrences(ss, '.');
boolean shouldParse = dots <= 1 && (dots == 0 ? len != (INTEGER_CONSTRAINT + 1) : len < (MAX_LENGTH + 1));
if (shouldParse) {
if (len > 1 && ss.lastIndexOf(".") != len - 1) {
try {
Double d = Double.parseDouble(ss);
if (d != null) {
et.setText(nf.format(d));
}
} catch (NumberFormatException e) {
}
}
} else {
et.setText(tmp);
}
et.addTextChangedListener(this); // reset listener
//tried to fix caret positioning after key type:
if (et.getText().toString().length() > 0) {
if (dots == 0 && len >= INTEGER_CONSTRAINT && moveCaretTo > INTEGER_CONSTRAINT) {
moveCaretTo = INTEGER_CONSTRAINT;
} else if (dots > 0 && len >= (MAX_LENGTH) && moveCaretTo > (MAX_LENGTH)) {
moveCaretTo = MAX_LENGTH;
}
try {
et.setSelection(et.getText().toString().length());
// et.setSelection(moveCaretTo); <- almost had it :))
} catch (Exception e) {
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
moveCaretTo = et.getSelectionEnd();
tmp = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = et.getText().toString().length();
if (length > 0) {
moveCaretTo = start + count - before;
}
}
}
Not 100% but you can use as a base and build on top of it ;)
EDIT: tried to polishing setting the caret position after text changed but it was more difficult than I estimated and reverted to setting the caret at the end after each char input. I left the code I started on for the caret maybe you can improve it?
There is a small mistake in above answer
I edited that one use the below code.
import java.math.RoundingMode;
import java.text.NumberFormat;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class DecimalTextWatcher implements TextWatcher {
private NumberFormat numberFormat = NumberFormat.getNumberInstance();
private EditText editText;
private String temp = "";
private int moveCaretTo;
private int integerConstraint;
private int fractionConstraint;
private int maxLength;
/**
* Add a text watcher to Edit text for decimal formats
*
* #param editText
* EditText to add DecimalTextWatcher
* #param before
* digits before decimal point
* #param after
* digits after decimal point
*/
public DecimalTextWatcher(EditText editText, int before, int after) {
this.editText = editText;
this.integerConstraint = before;
this.fractionConstraint = after;
this.maxLength = before + after + 1;
numberFormat.setMaximumIntegerDigits(integerConstraint);
numberFormat.setMaximumFractionDigits(fractionConstraint);
numberFormat.setRoundingMode(RoundingMode.DOWN);
numberFormat.setGroupingUsed(false);
}
private int countOccurrences(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
#Override
public void afterTextChanged(Editable s) {
// remove to prevent StackOverFlowException
editText.removeTextChangedListener(this);
String ss = s.toString();
int len = ss.length();
int dots = countOccurrences(ss, '.');
boolean shouldParse = dots <= 1 && (dots == 0 ? len != (integerConstraint + 1) : len < (maxLength + 1));
boolean x = false;
if (dots == 1) {
int indexOf = ss.indexOf('.');
try {
if (ss.charAt(indexOf + 1) == '0') {
shouldParse = false;
x = true;
if (ss.substring(indexOf).length() > 2) {
shouldParse = true;
x = false;
}
}
} catch (Exception ex) {
}
}
if (shouldParse) {
if (len > 1 && ss.lastIndexOf(".") != len - 1) {
try {
Double d = Double.parseDouble(ss);
if (d != null) {
editText.setText(numberFormat.format(d));
}
} catch (NumberFormatException e) {
}
}
} else {
if (x) {
editText.setText(ss);
} else {
editText.setText(temp);
}
}
editText.addTextChangedListener(this); // reset listener
// tried to fix caret positioning after key type:
if (editText.getText().toString().length() > 0) {
if (dots == 0 && len >= integerConstraint && moveCaretTo > integerConstraint) {
moveCaretTo = integerConstraint;
} else if (dots > 0 && len >= (maxLength) && moveCaretTo > (maxLength)) {
moveCaretTo = maxLength;
}
try {
editText.setSelection(editText.getText().toString().length());
// et.setSelection(moveCaretTo); <- almost had it :))
} catch (Exception e) {
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
moveCaretTo = editText.getSelectionEnd();
temp = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = editText.getText().toString().length();
if (length > 0) {
moveCaretTo = start + count - before;
}
}
}
use it as below..
itemCostEditText.addTextChangedListener(new DecimalTextWatcher(itemCostEditText, 6, 2));
You can make use of TextWatcher's afterTextChanged/onTextChanged methods to get notified for text changes and DecimalFormat to format input text
http://developer.android.com/reference/java/text/DecimalFormat.html
http://developer.android.com/reference/android/text/TextWatcher.html

How to automatically add commas to large numbers in Android?

I have a TextView that holds a number value (which is constantly being updated). Is there a method I can use to automatically add a comma if the number increases?
This is my current code:
String number = textView.getText().toString();
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###");
String formatted = formatter.format(amount);
textView.setText(formatted);
Takes an integer and returns a string formatted to the U.S. Locale
private String getFormatedAmount(int amount){
return NumberFormat.getNumberInstance(Locale.US).format(amount);
}
In: 10 Out: 10
In: 100 Out: 100
In: 1000 Out: 1,000
In: 10000 Out: 10,000
In: 100000 Out: 100,000
In: 1000000 Out: 1,000,000
You can use DecimalFormat as it even supports locales (some places use . instead of ,)
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String formatted = formatter.format(amount);
You can implements TextWatcher
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#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().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
To use it you can use
editText.addTextChangedListener(new NumberTextWatcher(editText));
Source : Roshka Dev Team

Unable to input zero after decimal point in Android EditText

I have an Android EditText which when a user puts a number, it edits the number and adds thousand separators using Decimal Format, but when one is inputting floating point numbers, i does not add zeros after the decimal point. so i can not input 1.000000008 because the zeros won't go on but other numbers do.
Is there any java DecimalFormat pattern that will allow a user to input a zero after the decimal point?
Here's the code for my EditText.
am = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
public void afterTextChanged(Editable s) {
amount.removeTextChangedListener(this);
amount2.setText(s.toString());
try {
int inilen, endlen;
inilen = amount.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
value = Double.parseDouble(v);
int cp = amount.getSelectionStart();
if (hasFractionalPart) {
amount.setText(df.format(n));
} else {
amount.setText(dfnd.format(n));
}
endlen = amount.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= amount.getText().length()) {
amount.setSelection(sel);
} else {
// place cursor at the end?
amount.setSelection(amount.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
amount.addTextChangedListener(this);
}
};
Rewrite
First, when a decimal symbol is present let's count how many zeros will be trimmed off by the formatter. (If we find a non-zero character after the decimal, we'll reset our count. For example 1.00200 only has two trailing zeros.) In onTextChanged():
int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
trailingZeroCount = 0;
if (index > -1)
{
for (index++; index < s.length(); index++) {
if (s.charAt(index) == '0')
trailingZeroCount++;
else {
trailingZeroCount = 0;
}
}
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
Next, append the appropriate number of zero's back on to the formatted String. In afterTextChanged():
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
amount.setText(df.format(n) + trailingZeros.toString());
} else {
amount.setText(dfnd.format(n));
}
Note: You haven't posted the formats you use, so I've had to make a few assumptions, but this is easily adaptable.

Categories

Resources