How to add empty space inside int?

Let's say I want to print the number 100000000. At first glance it’s hard to say how many millions this number represents. Is it 10 million or 100 million? How to make large numbers more readable in Java? Something like this, for example, would be great: 100 000 000 . You can immediately say that the number is 100 million.

+5
source share
6 answers

You can also try DecimalFormat;

 DecimalFormat formatter = new DecimalFormat("#,###"); System.out.println(formatter.format(100000)); 

Results:

 1000>>1,000 10000>>10,000 100000>>100,000 1000000>>1,000,000 
+9
source

You can try the following:

 String.format("%.2fM", yourNumber/ 1000000.0); 

Numbers in the format will be displayed here

 1,000,000 => 1.00M 1,234,567 => 1.23M 

EDIT: -

I know its later editing, but yes there is another way:

 private static String[] suff = new String[]{"","k", "m", "b", "t"}; private static int MAX_LENGTH = 4; private static String numberFormat(double d) { String str = new DecimalFormat("##0E0").format(d); str = str.replaceAll("E[0-9]", suff[Character.getNumericValue(str.charAt(str.length() - 1)) / 3]); while(str.length() > MAX_LENGTH || str.matches("[0-9]+\\.[az]")){ str = str.substring(0, str.length()-2) + str.substring(str.length() - 1); } return str; } 

Call this function and you will get the result as follows:

 201700 = 202k 3000000 = 3m 8800000 = 8.8m 
+3
source

Use the DecimalFormat class, see link for use.

To save you, I wrote what you basically need

 DecimalFormat myFormatter = new DecimalFormat("### ### ###"); String output = myFormatter.format(value); System.out.println(output); 
+2
source

You can use decimal format to format string

  DecimalFormat decimalFormat = new DecimalFormat("###,###,###"); System.out.println(decimalFormat.format(100000000)); 

It will print 100 million

For another input - say 1000, it will print 1000

+1
source

You might just want to use a string for this. If you need to do some calculations, just save it as an int until it is printed. Then, when it needs to be printed, convert it to a string, process the string so that it is read the way you would like, and print it.

0
source

what about the approach below, but it was supported in Java 7 and later:

int twoMillion = 2_000_000;

0
source

All Articles