Friday, August 24, 2012

Android EditText with number format input

Some applications require formatting the EditText's value while typing. I.E., a number that needs to be formatted with decimal and thousands separators.

We've created a little helper class implementing TextWatcher to do just that.

import java.text.DecimalFormat;
import java.text.ParseException;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

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, all you need to do is add a TextChangedListener to the EditText component.

editText.addTextChangedListener(new NumberTextWatcher(editText));


You can get the source code directly from GitHub.



43 comments:

  1. This works perfectly but it does not allow leading zeros after the decimal point
    e.g I can not type 1.000000003
    no zeros can go on after the decimal point
    please fix this

    ReplyDelete
    Replies
    1. Thank you so much Roshka but Paul is right , let me to fix this bug !
      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;
      }

      then 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));
      }

      Delete
    2. Thanks for your fix, and thank you Roshka.
      All of the best to you bunch of good people.

      Delete
    3. Hi 109862803127285470647.
      I'm sorry but it doesn't accept 0 (zero) after comma (symbol ,).

      My locale definitions are these:
      private final Locale locale = new Locale("pt", "BR");
      df = new DecimalFormat("##,###,###.##", new DecimalFormatSymbols(locale));
      dfnd = new DecimalFormat("#,###,###", new DecimalFormatSymbols(locale));

      Any help?
      Regards.

      Delete
  2. Wooooooooow! Pretty cool! this saved my ass. Thanks!

    ReplyDelete
  3. This is really good just have a problem that is appearing voids and would appear to be #,###.## instead of # ### ##. how can I do this? Thank you very much

    ReplyDelete
  4. Thank you very much...this saved my day

    ReplyDelete
  5. Thank you very much, i'm looking for it.Good man !

    ReplyDelete
  6. Hello, I served very good but if instead you pull me #, ## I want to pull me q #. ##.
    Change "," by "." ??? try changing it in the String but pretended not to recognize me.
    As you can do is ????

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi there.
      You gotta use locale. In my case, I have:
      private final Locale locale = new Locale("pt", "BR");
      df = new DecimalFormat("##,###,###.##", new DecimalFormatSymbols(locale));
      dfnd = new DecimalFormat("#,###,###", new DecimalFormatSymbols(locale));
      Then it will work...

      But I have a question below, for it doesn't accept 0 (zero) after comma (symbol ,).
      The correction proposed by 109862803127285470647 didn't work for me.

      Regards.

      Delete
  7. Como puedo haacer para que sea un punto en vez de una coma???

    Ejemplo: 1.85

    Trate cambiando el String pero no resulta, tambien probe poniendo un float pero no me salio tampoco.

    ReplyDelete

  8. Muchas gracias por la ayuda !!

    ReplyDelete
  9. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  10. Android developers develop apps for android phones. These phones run on the android operating system, and are able to download applications. The apps maximize the usefulness of smart phones.gerald winata gozali

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This rundown of the most prevalent free Android apps run the entire extent, demonstrating the range and the intensity of free Android apps when all is said in done.
    https://appcloner.app
    https://appcloner.net

    ReplyDelete
  13. Thanks For sharing this Superb article.I use this Article to show my assignment in college.it is useful For me Great Work. appcloner's website

    ReplyDelete
  14. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. hoverwatch price

    ReplyDelete
  15. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... legal entity identifier

    ReplyDelete
  16. At the point when we talk about telephone then in a split second Android come in our psyche, and we realize that Android stage is developing at a hurried rate around the world Bulk SMS Service Provider in Sharjah UAE

    ReplyDelete
  17. Developers can have two versions of an app, a free version and premium version consisting of additional features or even keep in-app purchases option. Placing ads on regularly visited apps can also help earn revenues. A combination of different options is also helpful.Best Mobile App development Companies in UK

    ReplyDelete
  18. Apps Geyser gives you facility to make ad-supported apps and make money through that. It has also a unique feature that make if different through other service provider that is sharing features, sharing of your apps to all major social network.Smart AudioBook Player Download

    ReplyDelete
  19. Usage of third party API: The 3rd party API is a device reliant, and it restricts the procedure of apps across special devices. The cross-platform IDE and SDK limit Android developers to use single API for the different device versions.https://techviola.com/why-people-read-mobile-spy-reviews

    ReplyDelete
  20. The application. should now be introduced effectively on your cell phone and you can utilize it like some other application. itools crack

    ReplyDelete
  21. A backlink is a link created when one website links to another. Backlinks are important to SEO & impact for higher ranking. In my 7+ years seo Career i see, without backlinks a website doesn't rank higher on google SERP.

    Get Your 300+ High Quality DoFollow Backlinks Here!

    Order Now with Full Confidence & 100% satisfaction.

    ReplyDelete
  22. With Brandsoo, it’s never been easier or more convenient to shop high quality domain names and professional logos that’ll instantly give your brand a leg up company brand names for sale and resonate with your audience! With many different domain sellers all competing for your business, you need to know where your business and brand will see.

    ReplyDelete
  23. Workplace diversity has been a prominent focus of the last decades, and diversity issues in the workplace the situation has improved - but only marginally. But what can we expect in 2020?

    ReplyDelete
  24. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

    ReplyDelete
  25. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

    ReplyDelete
  26. Situs judi bola online UFA88 Terpercaya, juga memiliki casino online seperti, baccarat, roulette, Judi slot online, sabung ayam dan Dadu online.

    ReplyDelete
  27. Adam the alien - Animated films A close encounter with a likable robot from another solar system leads to a star-crossed friendship Do aliens exist and an impossible intergalactic mission to save Extraterrestrial life the robot’s friends— despite overwhelming New cartoon movies odds.

    ReplyDelete
  28. TogelResult.info - Adalah Situs data hk Khusus yang menyediakan Daftar keluaran hk Result Nomor Togel dan Data hasil keluaran live draw hk seperti hk sgp sydney yang sudah terpercaya keluaran togel hk.

    ReplyDelete
  29. Shield Security Solutions Provides Ontario Security Training, Security Guard License or Security License in Ontario. Get Started Today

    ReplyDelete
  30. Website laten maken? Onze professionals bouwen een omzetverhogende, professionele én unieke website of webshop! Een website laten maken kan vandaag nog

    Website laten maken | webdesigner | website freelancer | webdeveloper | webdesigner

    ReplyDelete
  31. Discover antimicrobial protection that’s built-in right into the finish of select TikTok Locksmith Services.

    ReplyDelete
  32. Fire Alarm Houston, a RAB Security company, was founded in 2001. The purpose was to provide the Life Safety System to Houston, Harris County, Fort Bend County and the surrounding areas, a viable alternative to the overgrown nationwide companies. We pride ourselves on being the most trusted, well-rounded and customer-oriented security company in Houston, backed by over seven years of company history and national manufacturer brand names that you know and trust, such as Honeywell.

    ReplyDelete
  33. Fire Sprinkler Texas has been providing fire sprinkler installation, inspection and services for over 30 years in Texas, mainly in the Greater Houston, Dallas, San Antonio or Austin and surrounding area. If you are building a new facility which requires a fire sprinkler system by code, please give us a call for a free consultation.

    ReplyDelete