View Subcategory

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String rightPad(int number, int spaces) {
String numberString = String.valueOf(number);
return numberString + spaces(spaces - numberString.length());
}
String text = StringUtils.rightPad(String.valueOf(1024), 6)
String formatted = String.format("%-6d", 1024);
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [1024]).

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
java
String formatted = String.format("%3.2f", 7./8.);
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String leftPad(int number, int spaces) {
String numberString = String.valueOf(number);
return spaces(spaces - numberString.length()) + numberString;
}
String formatted = String.format("%10d", 73);
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [73]).