Better way to Format Currency Input editText?
I tested your method, but it fails when I use great numbers... I created this:
private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
[your_edittext].removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formatted;
[your_edittext].setText(formatted);
[your_edittext].setSelection(formatted.length());
[your_edittext].addTextChangedListener(this);
}
}
Kotlin variant:
private var current: String = ""
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
if (s.toString() != current) {
discount_amount_edit_text.removeTextChangedListener(this)
val cleanString: String = s.replace("""[$,.]""".toRegex(), "")
val parsed = cleanString.toDouble()
val formatted = NumberFormat.getCurrencyInstance().format((parsed / 100))
current = formatted
discount_amount_edit_text.setText(formatted)
discount_amount_edit_text.setSelection(formatted.length)
discount_amount_edit_text.addTextChangedListener(this)
}
}
Android EditText AddTextChangeListener Currency Format
Per this SO question Format EditText to currency with whole numbers I added setMaximumFractionDigits to 0 like so
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(current)) {
inputValue.removeTextChangedListener(this);
String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
String cleanString = s.toString().replaceAll(replaceable, "");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format((parsed));
current = formatted;
inputValue.setText(formatted);
inputValue.setSelection(formatted.length());
inputValue.addTextChangedListener(this);
}
Currency input with 2 decimal format
I think you can try the following:
Layout:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
/>
Activity:
EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(new NumberTextWatcher(editText, "#,###"));
with text watcher as the following:
public class NumberTextWatcher implements TextWatcher {
private final DecimalFormat df;
private final DecimalFormat dfnd;
private final EditText et;
private boolean hasFractionalPart;
private int trailingZeroCount;
public NumberTextWatcher(EditText editText, String pattern) {
df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.00");
this.et = editText;
hasFractionalPart = false;
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
if (s != null && !s.toString().isEmpty()) {
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
et.setText(df.format(n) + trailingZeros.toString());
} else {
et.setText(dfnd.format(n));
}
et.setText("$".concat(et.getText().toString()));
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel < et.getText().length()) {
et.setSelection(sel);
} else if (trailingZeroCount > -1) {
et.setSelection(et.getText().length() - 3);
} else {
et.setSelection(et.getText().length());
}
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
}
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) {
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;
}
}
}
Format currency string using EditText in Android
try this :
set TextChangedListner
as :
minimo.addTextChangedListener(new NumberTextWatcher(minimo));
create custom TextWatcher
as:
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";
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);
}
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;
}
}
}
Simple EditText currency formatter
Try to use a textwatcher :D
http://developer.android.com/reference/android/text/TextWatcher.html
Better way to Format Currency Input editText?
With this u can format the incoming String before its display,
so u can easily append a "€" and other stuff
Currency format for EditText
Library author here.
We've got a wiki page describing masks for texts with right-to-left alignment; this page includes a case similar to yours.
In short, try configuring your listener like this:
mask.rightToLeft = true
EditText to Input Money Amount
For your first problem follow this link
Thousand separator
For your second problem
add this to your editext
android:digits="0123456789"
android:inputType="numberDecimal"
And for your third problem you have to use TextWatcher like this
editText1.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (editText1.getText().toString().matches("^0") )
{
// Not allowed
Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
editText1.setText("");
}
}
@Override
public void afterTextChanged(Editable arg0) { }
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
});
Hw to Format Currency Input editText? Xamarin.Android
You could use the code below. I use the android:hint
to set the placeholder text($0.00) to EditText.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/myEditField"
android:hint="$0.00"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Code behind:
public class Activity2 : Activity
{
private EditText _editText;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.layout2);
_editText = FindViewById<EditText>(Resource.Id.myEditField);
_editText.AfterTextChanged += EditText_AfterTextChanged;
}
private void EditText_AfterTextChanged(object sender, AfterTextChangedEventArgs e)
{
var text = e.Editable.ToString();
_editText.AfterTextChanged -= EditText_AfterTextChanged;
var formatedText = ValueConverter(text);
_editText.Text = formatedText;
_editText.SetSelection(formatedText.Length);
_editText.AfterTextChanged += EditText_AfterTextChanged;
}
private static string ValueConverter(string text)
{
if (text.Length>5)
{
return string.Format("{0}{1}", "$0.0", text.Substring(4));
}
return string.Format("{0}{1}", "$0.0", text);
}
}
Related Topics
Android Gridlayout with Dynamic Number of Columns Per Row
Webview's HTML Button Click Detection in Activity
How to Reference Style Attributes from a Drawable
Android Mediaplayer Error (1, -2147483648)
Edittext with Number Keypad by Default, But Allowing Alphabetic Characters
Different Font Size of Strings in the Same Textview
Audiorecord Object Not Initializing
How to Disable the Clear Data Button in Application Info of Manage Application
Android 2.2 Mediaplayer Is Working Fine with One Shoutcast Url But Not with the Other One
How to Create and Read Log on Android Devices
How to Change the Color of Header Bar and Address Bar in Newest Chrome Version on Lollipop
Customize Android Facebook Login Button
Schedule a Work on a Specific Time with Workmanager
Show an Alert Dialog in Broadcast Receiver After a System Reboot
How to Record Phone Calls in Android