RSS

Android Format Currency Input editText

21 Feb

I have an editText, starting value is $0.00. When you press 1, it changes to $0.01. Press 4, it goes to $0.14. Press 8, $1.48. Press backspace, $0.14, etc.

That works, the problem is, if somebody manually positions the cursor, problems occur in the formatting. If they were to delete the decimal, it won’t come back. If they put the cursor in front of the decimal and type 2, it will display $02.00 instead of $2.00. If they try to delete the $ it will delete a digit instead, for example.

<code> mEditPrice.setRawInputType(Configuration.KEYBOARD_12KEY);
public void priceClick(View view) {
mEditPrice.addTextChangedListener(new TextWatcher(){
DecimalFormat dec = new DecimalFormat("0.00");
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
</code>
<code> if(!s.toString().equals(current)){
mEditPrice.removeTextChangedListener(this);

String cleanString = s.toString().replaceAll("[$,.]", "");
</code>
<code> BigDecimal parsed = new BigDecimal(cleanString).setScale(2,BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR);
 String formated = NumberFormat.getCurrencyInstance().format(parsed);</code>
<code>        current = formated;       </code>
<code> mEditPrice</code>.setText(formated);       
<code> mEditPrice</code>.setSelection(formated.length());
<code>mEditPrice</code>.addTextChangedListener(this);
<code>    }</code>
<code>
}
});</code>

Referenced by: http://stackoverflow.com/questions/5107901/better-way-to-format-currency-input-edittext

Advertisements
 
Leave a comment

Posted by on February 21, 2012 in Android

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: