Karthick
Karthick

Reputation: 193

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?

Upvotes: 10

Views: 10408

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69339

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

Upvotes: 19

Related Questions