All -
I have a TextWatcher that formats the EditText as currency:

private String current ="";public void onTextChanged(CharSequence s, int start, int before, int count) { if(!s.toString().equals(current)){ editText$.removeTextChangedListener(this); String cleanString = s.toString().replaceAll("[$,.]",""); double parsed = Double.parseDouble(cleanString); String formated = NumberFormat.getCurrencyInstance().format((parsed/100)); current = formated; editText$.setText(formated); editText$.setSelection(formated.length()); editText$.addTextChangedListener(this); }}

This works fine, the problem is that my EditText only expects integers, so I can't let the user enter cents. So instead of 0.1 vs. 0.12 instead of 1.23 compared to 12.34, how can I get rid of the decimal point but keep the comma? thanks.

Solution:

If you don't mind removing the period and trailing zeros, you can do this:

mEditText.addTextChangedListener(new TextWatcher() { private String current =""; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!s.toString().equals(current)) { annualIncomeEntry.removeTextChangedListener(this); String cleanString = s.toString().replaceAll("[$,]",""); if (cleanString.length() > 0) { double parsed = Double.parseDouble(cleanString); NumberFormat formatter = NumberFormat.getCurrencyInstance(); formatter.setMaximumFractionDigits(0); current = formatter.format(parsed); } else { current = cleanString; } annualIncomeEntry.setText(current); annualIncomeEntry.setSelection(current.length()); annualIncomeEntry.addTextChangedListener(this); } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } });

This sets the maximum number of decimal places to zero for the number formatter, removing all trailing zeros and periods. I also divide by 100 so that all numbers entered are integers.

Also make sure that the EditText's inputType is"number", otherwise this will crash if the user tries to enter a non-numeric character.

java - currency to format EditText as integer Related posts

  1. [happyz-Java]MATLAB-FM simulation 04

    Analysis of simulation resultsFM signal modulationThe following are the time domain and frequency domain graphs of the modulated and modulated signals when mf=0.5, mf=1 and mf=3 respectively: the modulated signal time domain graphs of the modulated signal and the carrier signal when mf=0.5 (the adde ...

  2. use java.util.Currency in GWT?

    I'm developing a GWT application and we have introduced a Money class that contains java.util.Currency. The only problem is that GWT doesn't seem to support this class.I did a google search and found this code in the GWT source code, but I'm not quite sure what the"jat numberformat-r2942"library is, ...

  3. Java currency formatter: force formatting with currency symbols

    I use spring currency formatter to format value according to currency codepublic String format(Number number, String currencyCode){ CurrencyFormatter formatter = new CurrencyFormatter(); formatter.setCurrency(Currency.getInstance(currencyCode)); return formatter.print(number, Locale.getDefault()); } ...

  4. php-How to use community URL styles such as Last.FM or Wikipedia?

    I am trying to understand how to deal with characters in URLs, this is because I am building a site where users can store content and go to the content page by digging its name in the URL.So, like Wikipedia or Last.FM website.I saw on the website that users can write something similar to http://it.w ...

  5. java – Last.fm will not return artist pictures

    I am trying to get and apply artist image from Last.fm to ImageView, but no image is returned. I am not sure what I am doing wrong here.private void setLastFmArtistImage() { try { String imageurl ="http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="+ URLEncoder.encode("Andrew Bird ...

  6. java-Convert from String to BigDecimal to perform mathematical operations on currency

    I am working on a project that needs to perform some simple mathematical operations on currency, but it arrives as a String. I am new to Java/Android, so I am looking for help converting from String to a data type suitable for this operation. At first I Think Float is correct, but after reading othe ...

  7. How to summarize currency value in Java?

    Okay, here is my problem. Basically I have this problem.I have a number like .53999999. How can I round it to 54 without using any mathematical functions?I guess I have to multiply by 100 to scale it, then divide by? Something like that?The problem is the money. Suppose I have 50.5399999 dollars, I ...

  8. How to add a new currency code to Java?

    The ISO 4217 code of the Chinese currency is CNY. Because of the restrictions on global free transactions using this currency, there is also a second"offshore"currency equivalent called CNH. Wikipedia has a total of summary.CNH is not in ISO 4217, but I want to be able to use it in my application wi ...

  9. recommendation algorithm ---FM algorithm;

    1. FM algorithm: 1. The logistic regression has crossed features. The algorithm complexity is optimized from O(n^3)->O(k*n^2)->O(k*n). 2. Essence: Each feature has a k-dimensional vector, which represents that each feature has k ulterior pieces of information. (FFM: In the face of ...

  10. xLearn source code analysis of FM's CalcScore implementation

    Write in frontxLearn is an efficient machine learning algorithm library implemented by Chao Ma, here is the github address:https://github.com/aksnzhy/xlearnFM is an outstanding model in the field of CTR in machine learning. It was first proposed by Steffen Rendle of Konstanz University (now at Googl ...

  11. FM algorithm principle and python actual combat

    1. Introduce FMIn traditional linear models such as LR, each feature is independent. If you need to consider the direct interaction between the feature and the feature, you may need to cross-combinate the feature manually; nonlinear SVM can perform kernel mapping on the feature, but in the feature I ...

  12. java – How to get currency name by country code?

    I want to get the currency name by country/region code. I use the following code to get the country/region code:TelephonyManager manager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); String countrycode=manager.getNetworkCountryIso(); System.out.println("---->"+countrycode+"<----");N ...

  13. java - currency to format EditText as integer

    All - I have a TextWatcher that formats the EditText as currency:private String current ="";public void onTextChanged(CharSequence s, int start, int before, int count) { if(!s.toString().equals(current)){ editText$.removeTextChangedListener(this); String cleanString = s.toString().replaceAll("[$,.]" ...

  14. java-Android currency symbol sorting

    I am using a device in a non-English language environment, and the English currency is formed as follows:$ 1If I have an English locale, I will get Euro currency:1 Eurouseformat.setCurrency(Currency.getInstance(currency));return format.format(amount);Found in the documentation:http://developer.andro ...

  15. java-character encoding issues related to currency symbols

    I am creating a web application. I am developing an application using linux (fedora 16) and the technology used is spring MVC. It is a maven project. When I run the application in a debugging environment, the application works fine Working and displaying special characters correctly I want to displa ...

  16. use last.fm API in JavaScript

    I have very little experience with web development. I have a little experience with HTML and am now learning JavaScript. I created a program in Java using Java's last.fm library. I am able to get user info, artist info and venue info. Now , I want to try to do this in a web page and that's where my ...

Recent Posts

  1. php-Laravel-Passport API integration|Error: {"message": "Unidentified."}

    I am new to Laravel. I just started learning Laravel passport integration using this reference link.Below is my route file api.phpRoute::post('login', 'API\[email protected]'); // this is working fineRoute::post('register', 'API\Pas[email protected]'); // this is working fineRoute::gro...

  2. If I extend a c# interface, can I answer the phone?

    In this question, I mentioned Unity3D, but it generally applies to c#.Unity3D has an interface that looks like this...public class SomeRobot:MonoBehaviour, IPointerDownHandler {public void OnPointerDown(PointerEventData data) {Debug.Log("Gets called whenever someone touches the screen...");}No probl...

  3. javascript-How to pass the hidden field value to the codeigniter controller via ajax

    I have a view file that contains buttons (links):SaveElsewhere in this view, I also declared some hidden fields in a form containing my userid and vacancyid.echo form_input(dataHiddenArray('userid', $this->auth_user_id)); echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy...

  4. Use Drive python API to set up "publish to the web" in Google spreadsheets

    I'm trying to simulate clicking"Publish to the web"->"Start publishing now"in Google Docs using the Python version of Google Drive API. Based on my vague understanding of the document, I think this should work:service.revisions().update(fileId = newfile['id'], revisionId='head', body={'published'...

  5. java – How to use enum and jpa as data members of persistent entities?

    Please use jum as the best practice for the data member of the persistent entity and"how"to use enum. What is the best practice? I want to stick to"C","O"from the enumeration. (code). If this is not the right way, please suggest.Enum defination is –public enum Status{CLOSED ("C")OPEN ("O")private fi...

  6. amazon-web-services-Error adding environment variables to NodeJS Elastic Beanstalk

    My configuration continued until yesterday. I added nginx NodeJS https redirect extension from AWS. Now, when I try to add a new environment variable through Elastic Beanstalk configuration, I get this error:[Instance: i-0364b59cca36774a0] Command failed on instance. Return code: 137 Output: + rm -f...

  7. python-NLTK-no module named corpus

    After installing NLTK and NLTK-DATA with PIP, I run python and input it from nltk.corpus import cmudict. But when I write a script like this:from nltk.corpus import cmudictd = cmudict.dict()def nsyl(word): return [len(list(y for y in x if y[-1].isdigit())) for x in d[word.lower( )]]print nsyl("hello...

  8. algorithm notes-binary search

    [Binary search] Binary search is aimed at an ordered set of data, and the search idea is somewhat similar to the divide and conquer idea. Each time, by comparing with the middle element of the interval, the interval to be searched is reduced to half of the previous one, until the element to be searc...

  9. android-When reading the NDEF tag, it is displayed in the "NFC service" instead of the content in the app

    I am trying to use ADT to read NDEF tags from an Android application.The code is exactly the same as in this tutorial.It displays the content correctly, but instead of opening my app, it shows a clone of my app (same user interface), and it is called"NFC service"with the Bluetooth icon.The problem i...

  10. About java terminology, English abbreviations are necessary

    1. What are the functions of Action layer, Service layer, Modle layer and Dao layer in JAVA? (The service layer described below is biz) First of all, this is the most basic layering method now, combined with the SSH architecture. The modle layer is the entity class of the corresponding database tabl...