Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left-pad an integer with spaces?

How to format an Integer value without leading zero? I tried using decimal format but I can't achieve exact result:

DecimalFormat dFormat=new DecimalFormat("000");

mTotalNoCallsLbl.setText(""+dFormat.format(mTotalNoOfCallsCount));
mTotalNoOfSmsLbl.setText(""+dFormat.format(mTotalNoOfSmsCount));
mSelectedNoOfCallsLbl.setText(""+dFormat.format(mSelectedNoOfCallLogsCount));
mSelectedNoOfSmsLbl.setText(""+dFormat.format(mSelectedNoOfSmsCount));

I'm getting these output :

500
004
011
234

but I want these:

500
  4
 11
234

My question is how to replace the zeroes with spaces?

like image 278
Karthick Avatar asked Sep 23 '14 07:09

Karthick


People also ask

How can I pad a string with zeros on the left?

To pad zeros to a string, use the str. zfill() method. It takes one argument: the final length of the string you want and pads the string with zeros to the left.

How do you add spacing in printf?

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following. char *ptr = "Hello"; printf("%40s\n", ptr); That will give you 35 spaces, then the word "Hello".

How do you put a space at the end of a string in Java?

format("%-20s", str); In a formatter, % introduces a format sequence. The - means that the string will be left-justified (spaces will be added at the end of the string). The 20 means the resulting string will be 20 characters long.

What is left padding in Java?

The leftPad(final String str, final int size, final char padChar) method. This method is used to pad the given character to the left side of the string. The number of characters padded is equal to the difference of the specified size and the length of the given string.


1 Answers

Looks like you want to left-pad with spaces, so perhaps you want:

String.format("%3d", yourInteger);

For example:

int[] values = { 500, 4, 11, 234 };

for (int v : values) {
  System.out.println(String.format("%3d", v));
}

Output:

500
  4
 11
234
like image 180
Duncan Jones Avatar answered Oct 19 '22 17:10

Duncan Jones