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?
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.
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".
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With