Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a String number to have commas in android Edit Field

For what function I can use in android to display the number into different formats.

For eg: If I enter 1000 then it should display like this 1,000. If I enter 10000 then it should display like this 10,000. If I enter 1000000 then it should display like this 1,000,000.

Please guide me.

like image 767
user1082964 Avatar asked Nov 05 '13 11:11

user1082964


People also ask

How can I format a string number to have commas?

For format String "%,. 2f" means separate digit groups with commas and ".

What is string format in Android?

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this: Resources res = getResources(); String text = res.getString(R. string.welcome_messages, username, mailCount);

How do you add a comma to a number string in Java?

You can use java. util. text. NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them.


2 Answers

You could use DecimalFormat and just format the number

DecimalFormat formatter = new DecimalFormat("#,###,###"); String yourFormattedString = formatter.format(100000); 

The result will be

  • 1,000,000 for 1000000
  • 10,000 for 10000
  • 1,000 for 1000

Update 12/02/2019

This String.format("%,d", number) would be a better(less hardcoded) solution as indicated in the comments below by @DreaminginCode so I thought I would add it here as an alternative

like image 68
the-ginger-geek Avatar answered Oct 13 '22 06:10

the-ginger-geek


try this one hope it will help.

 System.out.println(NumberFormat.getNumberInstance(Locale.US).format(1000)); 
like image 37
Sandeep Avatar answered Oct 13 '22 06:10

Sandeep