Monday, March 19, 2012

Formatting currency value in Edittext

When we work with the currency   we need to use ',' separator in appropriate places  .  For example 1500 as 1,500. For formatting the currency value, we can use NumberFormat Class . Also we need to add a textchange listener to that edit text. Format the value while we get a call in afterTextChanged() method in addTextChangedListener . A simple example below

mDishPrice.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 }

 @Override
 public void afterTextChanged(Editable s) {
  /***
   * No need to continue the function if there is nothing to
   * format
   ***/
  if (s.length() == 0){
   return;
                }

  /*** Now the number of digits in price is limited to 8 ***/
  String value = s.toString().replaceAll(",", "");
  if (value.length() > 8) {
   value = value.substring(0, 8);
  }
  String formattedPrice = getFormatedCurrency(value);
  if (!(formattedPrice.equalsIgnoreCase(s.toString()))) {
   /***
    * The below given line will call the function recursively
    * and will ends at this if block condition
    ***/
   mDishPrice.setText(formattedPrice);
   mDishPrice.setSelection(mDishPrice.length());
  }
 }
});
/**
 * 
 * @param value not formated amount
 * @return Formated string of amount (##,##,##,###).
 */
public static String getFormatedCurrency(String value) {
 try {
  NumberFormat formatter = new DecimalFormat("##,##,##,###");
  return formatter.format(Double.parseDouble(value));
 } catch (Exception e) {
  e.printStackTrace();
 }
 return "";
}

No comments:

Post a Comment