How to Use Format Strings (%)

·

1 min read

%d

Data Type: Decimal byte, short, int, long

Example Usage:

String temp = String.format("%d", 29);
System.out.println(temp); // 29

%[Number]d

Data Type: Decimal byte, short, int, long

Example Usage:

String temp = String.format("%5d", 29);
System.out.println(temp); // _ _ _29

%o

Data Type: Octal byte, short, int, long

Example Usage:

String temp = String.format("%o", 10);
System.out.println(temp); // 12

%x

Data Type: Hexadecimal byte, short, int, long

Example Usage:

String temp = String.format("%x", 10);
System.out.println(temp); // a

%f

Data Type: Floating-point float, double

Example Usage:

String temp = String.format("%f", 123.4567);
System.out.println(temp); // 123.456700

%.[Number]f

Data Type: Floating-point float, double

Example Usage:

String temp = String.format("%.2f", 123.4567);
System.out.println(temp); // 123.46

%e

Data Type: Floating-point in scientific notation

Example Usage:

String temp = String.format("%e", 874.9163);
System.out.println(temp); // 8.749163e+02

%s

Data Type: String

Example Usage:

String temp = String.format("%s", System.lineSeparator());
System.out.println(temp); // Line Break

%c

Data Type: Character

Example Usage:

String temp = String.format("%c", 'y');
System.out.println(temp); // y