Table of contents
1. Usage of String.format() function
2. Commonly used conversion symbols
1. Usage of String.format() function
The String.format() function is similar to the printf() function, which can format or process strings. The printf() function prints the result directly, and the String.format() function can return the formatted string .
For example
public class Demo {
public static void main(String[] args) {
int sum = 200;
String s = String.format("sum = %d", 10);
System.out.println(s);
}
}
operation result
2. Commonly used conversion symbols
conversion character | illustrate | example |
---|---|---|
%c | character type | ‘a’ |
%s | string type | “hello” |
%b | Boolean type | true |
%d | integer type (decimal) | 10 |
%f | floating point | 3.14 |
%x(X) | integer type (hexadecimal) | a(A) (10 in decimal) |
%o | integer type (octal) | 12 (10 in decimal) |
%% | percentage type | %% (% is a special character, %% will display %) |
%e | index type | 1.2e+5 |
example
public class Demo {
public static void main(String[] args) {
String s1 = String.format("%c %s %b %d",'a', "abc", true, 20);
System.out.println(s1);
String s2 = String.format("%f,%x,%o,%%,%e",3.1,10,10,3.1e+4);
System.out.println(s2);
}
}
operation result
3. Common logos
logo | illustrate | example |
---|---|---|
+ | make a positive number show a positive sign | ("%+d", 12) |
- | Left-aligned, spaces are filled for insufficient digits (right-aligned when no negative sign is added) | ("%-5d", 12) ("%5d", 12) |
0 | Add 0 in front of the number | ("%05d", 12) |
space | Fill spaces where there are not enough digits | ("% 5d", 12) |
# | For hexadecimal numbers, add ox; for octal numbers, add o; for floating point numbers, include a decimal point | ("%#x",12) ("%#o", 12) |
, | Group numbers with , in groups of three (often used to display amounts) | ("%,f",122222.22) |
example
public class Demo {
public static void main(String[] args) {
String s1 = String.format("%+d,%-5d,%5d,%05d,% 5d", 12, 12, 12, 12 ,12, 12);
System.out.println(s1);
String s2 = String.format("%#x %#o %,f",12,12,122222.22);
System.out.println(s2);
}
}
operation result