Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string align to right

Tags:

java

formatter

I have an array of these numbers

61672 8414449 264957 

I use a DecimalFormat object like this

DecimalFormat formatter = new DecimalFormat("###,### bytes"); 

to get these results

61,672 bytes 8,414,449 bytes 264,957 bytes 

but I need the results to be aligned to right like the following

   61,672 bytes 8,414,449 bytes   264,957 bytes 

Your help is already appreciated.

like image 973
David Weng Avatar asked May 21 '11 07:05

David Weng


People also ask

How do you align a string in Java?

For right align use +ve %ndformat("%4d", i * j); //each number formatted to a width of 4 so use %4d in the format method. } System. out. println(); // To move to the next line. }

How do you right justify a string in Java?

To get a right-justified column the same sequence of characters are used, except for the minus sign. To get a newline %n is used. Note that the characters are surrounded with double quotes.

What does %d do in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.

What does %n do in Java?

By using %n in your format string, you tell Java to use the value returned by System. getProperty("line. separator") , which is the line separator for the current system.


1 Answers

You can wrap it into a String.format call like this:

String.format("%15s", formatter.format(i)) 
like image 51
Howard Avatar answered Sep 23 '22 16:09

Howard