[Java] [Java] Specify a format with printf and output %s, %d, %f [Format specifier]

1 minute read

Function that specifies the display format

When using a function with f at the end, such as printf (), it is possible to specify the display format and output.

I haven’t used it until now, but I can’t do anything without trying it myself, so let’s try it.

Meaning of each format

Specifier corresponding type description
%s string Output string
%d int integer output in decimal
%f float Output real number

Example of use

public class MyApp {
It's a sequel.
public static void main(String[] args) {
int score = 50; // %d corresponds
double height = 165.8; // %f corresponds
String name = "mako"; // %s corresponds

System.out.printf("name: %s, score: %d, height: %f\n", name, score, height);
System.out.printf("name: %-10s, score: %10d, height: %5.2f\n", name, score, height);

String s = String.format("name: %-10s, score: %-10d, height: %5.2f\n", name, score, height);
System.out.println(s);
}
}

Execution result


name: mako, score: 50, height: 165.800000
name: mako ,score: 50, height: 165.80
name: mako ,score: 50 ,height: 165.80

It wasn’t too shy to understand the meaning of the alphabet

  1. %s s is a String
  2. f in %f is float
  3. %d d is Decimal (decimal)

With that in mind, it wasn’t something I would shy away from. However, it seems a little complicated for beginners to write the arguments of printf, but just pass the variable names as arguments in order afterwards.

If you calm down and try a few yourself, you will understand immediately.

Display digits can be specified, and right justification and left justification can also be specified

%10s // 10 digits prepared and right justified
%-10s // 10 digits prepared and left justified
%10s // 10 digits prepared and right justified
%-10s // 10 digits prepared and left justified
%5.3f //Display the integer part with 5 digits and the decimal part with 3 digits

Regarding the last %5.3f, I feel that there is not much meaning even if the integer part is specified. .. ..

public static void main(String[] args) {
  double f = 12345.12345;
System.out.printf("%f\n", f);
System.out.printf("%.3f\n", f);
System.out.printf("%3.3f\n", f);
  }
}

Execution result


12345.123450
12345.123
12345.123

If the number of digits is greater than the specified number of digits, it will be displayed as is. Only a minority changes.

The display is the same for %.3f and %3.3f.

Tags:

Updated: