How to left-pad an integer with spaces?

本小妞迷上赌 提交于 2020-01-13 09:16:33

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25989541/how-to-left-pad-an-integer-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!