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.
This works perfectly but it does not allow leading zeros after the decimal point
ReplyDeletee.g I can not type 1.000000003
no zeros can go on after the decimal point
please fix this
Thank you so much Roshka but Paul is right , let me to fix this bug !
Deletein 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));
}
Thanks for your fix, and thank you Roshka.
DeleteAll of the best to you bunch of good people.
Hi 109862803127285470647.
DeleteI'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.
Great Article android based projects
DeleteJava Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
Wooooooooow! Pretty cool! this saved my ass. Thanks!
ReplyDeleteThis 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
ReplyDeleteThank you very much...this saved my day
ReplyDeleteThanks, work for me.
ReplyDeleteThanks a lot! It's very useful.
ReplyDeleteThank you very much, i'm looking for it.Good man !
ReplyDeleteHello, I served very good but if instead you pull me #, ## I want to pull me q #. ##.
ReplyDeleteChange "," by "." ??? try changing it in the String but pretended not to recognize me.
As you can do is ????
This comment has been removed by the author.
DeleteHi there.
DeleteYou 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.
Como puedo haacer para que sea un punto en vez de una coma???
ReplyDeleteEjemplo: 1.85
Trate cambiando el String pero no resulta, tambien probe poniendo un float pero no me salio tampoco.
ReplyDeleteMuchas gracias por la ayuda !!
Perfect - Thanks a lot!
ReplyDeleteHi, 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.
ReplyDeleteAndroid 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
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis 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.
ReplyDeletehttps://appcloner.app
https://appcloner.net
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
ReplyDeleteThanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. hoverwatch price
ReplyDeleteYou 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
ReplyDeleteAt 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
ReplyDeleteDevelopers 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
ReplyDeleteApps 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
ReplyDeleteUsage 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
ReplyDeleteThe application. should now be introduced effectively on your cell phone and you can utilize it like some other application. itools crack
ReplyDeleteA 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.
ReplyDeleteGet Your 300+ High Quality DoFollow Backlinks Here!
Order Now with Full Confidence & 100% satisfaction.
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.
ReplyDeleteWorkplace 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?
ReplyDeleteForex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD
ReplyDeleteForex Signals Forex Strategies Forex Indicators Forex News Forex World
Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD
ReplyDeleteForex Signals Forex Strategies Forex Indicators Forex News Forex World
Hey! Finally we are launch 150+ High DA Dofollow Quality Backlinks here! Order Now and Boost your website ranking.
ReplyDeleteManual Backlinks | Quality Backlinks | Dofollow Backlinks | High Quality Backlinks
Thank you!
DigiPeek
Situs judi bola online UFA88 Terpercaya, juga memiliki casino online seperti, baccarat, roulette, Judi slot online, sabung ayam dan Dadu online.
ReplyDeleteAdam 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.
ReplyDeleteTogelResult.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.
ReplyDeleteShield Security Solutions Provides Ontario Security Training, Security Guard License or Security License in Ontario. Get Started Today
ReplyDeleteShield Security Solutions Offers Security Guard License Training across the province of Ontario. Get Started Today!
ReplyDeleteSecurity Guard License | Security License | Ontario Security license | Security License Ontario | Ontario Security Guard License | Security Guard License Ontario
Website laten maken? Onze professionals bouwen een omzetverhogende, professionele én unieke website of webshop! Een website laten maken kan vandaag nog
ReplyDeleteWebsite laten maken | webdesigner | website freelancer | webdeveloper | webdesigner
Discover antimicrobial protection that’s built-in right into the finish of select TikTok Locksmith Services.
ReplyDeleteFire 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.
ReplyDeleteFire 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.
ReplyDeleteWe are a full service internet marketing company in the Pittsburgh area, that specializes in providing affordable internet marketing solutions for small businesses.
ReplyDeleteOur team builds and enhances local business listings and seo search engine optimization. This Pittsburgh SEO company service drives lead generation and brand recognition.
Our goal is long term mutual relationships with small business owners, providing customized internet marketing services.
Property Adjuster - We specialize in helping families with their property damage claim. Take comfort knowing I will do everything I can to help you. Ask for Mike
ReplyDeleteKeeping up with Brilyent Kelly. Get Exlcusive offers and see the latest Music and news & Follow me on instragram Celebrity.
ReplyDeleteThanks Dev Team for sharing this important information. Waiting for next update.
ReplyDeleteonline classified ads platform
Royal Moving Co. is an affordable Los Angeles Moving Company for both local moving, Movers near me long distance moving and packing services throughout Los Angeles county. We Moving company near me offer professional, affordable service.
ReplyDelete