简体   繁体   中英

How to have Android automatically add commas?

String number = textView1.getText().toString();
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String formatted = formatter.format(amount);

textView1.setText(formatted);

I'm using this code to have it add commas to a textview in my application. But when I run my app it does absolutely nothing? What am I doing wrong here?

Ok. I tested a bit around and I got the solution.

String in = "123456789";            
double amount = Double.parseDouble(in);         
amount = amount / 10;       
DecimalFormat df = new DecimalFormat(".00");        
String formatted = df.format(amount);           
System.out.println(formatted);

==>> output is here: 12345678,90 you have to divide your double to get your comma.

The double you get with your version is 123456789.00 --> by dividing it by 10 .. or whatever you like it gets 12345678.90 ... in that case a simple

String.valueOf(amount);

would be sufficient. But if you change the DecimalFormat to

DecimalFormat df = new DecimalFormat(",###.00");

your output is ==> 12.345.678,90

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM