Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add empty space inside int?

Let's say I want to print the number 100000000. At first sight it is difficult to tell how many millions this number is representing. Is it 10 million or 100 million? How can I make big numbers in Java look more readable? Something like this for instance would be great: 100 000 000. You can tell right away that the number is 100 million.

like image 594
Sing Sandibar Avatar asked Apr 21 '15 17:04

Sing Sandibar


People also ask

How do you add a space to an int array?

you can't. a space is not a valid int. You can't do that with an int array. If you use an Integer array you can replace the value with a null .

How do you add a space in an integer in Java?

Manual Spacing For instance, to output three different integers, "i," "j" and "k," with a space between each integer, use the following code: System. out. println(i + " " + j + " " + k);

How do I add blank spaces to a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').


2 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
like image 58
Dhaval Patel Avatar answered Sep 28 '22 05:09

Dhaval Patel


You can try like this:

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

This will display the numbers in the format

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

EDIT:-

I know its a late edit but yes there is one more 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]+\\.[a-z]")){
        str = str.substring(0, str.length()-2) + str.substring(str.length() - 1);
    }
    return str;
}

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

201700 = 202k
3000000 = 3m
8800000 = 8.8m
like image 24
Rahul Tripathi Avatar answered Sep 28 '22 05:09

Rahul Tripathi