Sometimes it is important to guarantee width. Like when we wish to display tabular data on a simple text file. E.g.
Unit Price Quantity Total Price 1.50 1000 1500 12.25 100 1225 3.10 10 31This is easy to achieve when we format each column with a fix length. E.g. Format unit price column using 10 characters, format quantity column using 8 characters, etc.
The simplest way to solve this problem is to code the logic ourselves. We can use a StringBuilder to pad the prefix and append the number last. Below is an example using the character zero (0) to pad the number.
public class Test { public static void main(String[] args) { int number = 15; String numberAsString = String.valueOf(number); StringBuilder sb = new StringBuilder(); while(sb.length()+numberAsString.length()<10) { sb.append('0'); } sb.append(number); String paddedNumberAsString = sb.toString(); System.out.println(paddedNumberAsString); } }
The code formats the String to 10 characters long.
Here is the sample output.
0000000015
Here is a simple trick that uses substring to determine the String to pad the number. Here is an example that shows 3 different numbers to show that the logic works.
public class Test { public static void main(String[] args) { // 1 digit int number = 1; String numberAsString = String.valueOf(number); String paddedNumberAsString = "0000000000".substring(numberAsString.length()) + numberAsString; System.out.println(paddedNumberAsString); // 2 digits number = 12; numberAsString = String.valueOf(number); paddedNumberAsString = "0000000000".substring(numberAsString.length()) + numberAsString; System.out.println(paddedNumberAsString); // 3 digits number = 125; numberAsString = String.valueOf(number); paddedNumberAsString = "0000000000".substring(numberAsString.length()) + numberAsString; System.out.println(paddedNumberAsString); } }Here is the sample output
0000000001 0000000012 0000000125
public class Test { public static void main(String[] args) { int number = 153; String numberAsString = String.format("%010d", number); System.out.println(numberAsString); } }Here is the output:
0000000153Here is a modified code that uses space instead of zero to pad the resulting String.
public class Test { public static void main(String[] args) { int number = 153; String numberAsString = String.format("% 10d", number); System.out.println(numberAsString); } }Here is the output:
153