Sometime, you may want to format an integer
or a long
value into a fixed width String
. You need to display the value in fixed width especially in reports where you want to keep the numbers in aligned (e.g. 3456 as 0003456
and 1234 as 0001234
).
Other than that, you may also want to format the integer
value for a better visibility. For example, to display integer
value as a document number (e.g. 12345678 as 00-01234-5678
), for example an account number.
The Java.format()
is not flexible enough to solve my problem. At least it cannot be used to format a fixed length document number in the format I want: XX-XXXX-XXXX
. Therefore I decide write my own format function.
The following function format a integer
value into a fixed length String
.
public class IntegerUtil { public static String formatFixedWidth(int value, int width) { char[] chars; int i; int c; chars = new char[width]; for (i = 0; i < width; i++) { c = value % 10; chars[width-i-1] = (char)('0' + c); value = value / 10; } return new String(chars); } }
To format the document number like the one I said above, you simply modify the source code above to add one or two lines code to append a “-” to the String when the loop iterate to the place where you want to put the “-“. Remember to increase the characters buffer as well.
The following function shows a sample implementation of my document number format.
public class IntegerUtil { public static String formatDocumentNumber(int value) { char[] chars; int i; int c; int size; size = 10+2; chars = new char[size]; for (i = 0; i < size; i++) { if (i == 4 || i == 9) { chars[width-i-1] = '-'; continue; } c = value % 10; chars[width-i-1] = (char)('0' + c); value = value / 10; } return new String(chars); } }
Bowmessage says
Using Format is a good solution for some leading 0s! Just format with the String “%05d”, 5 being the fixed-width of the String representation.
szehau says
Hi, you can test the Java String.format againts my function, you will see my code is faster. Second my code is more flexible. I can format an integer value (e.g. 1234567) into the format I want (e.g. 12-34-567).