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");
public void afterTextChanged(Editable arg0) {
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
public void onTextChanged(CharSequence s, int start,
int before, int count) {
<code> if(!s.toString().equals(current)){

String cleanString = s.toString().replaceAll("[$,.]", "");
<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>    }</code>

Referenced by:

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: Logo

You are commenting using your 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: