[Java] Output by specifying the format with printf% s,% d,% f [Format specifier]

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 before, but I can't do anything without trying it myself, so let's try it while trying it.

The meaning of each format

Specifier Corresponding type Description
%s string Output string
%d int Output integer in decimal
%f float Output real numbers

Example of use

public class MyApp {
		
	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

If I understood the meaning of the alphabet, I wouldn't be too shy.

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

With this in mind, it wasn't something I would avoid. However, the way to write the arguments of printf seems to be a little complicated for beginners, but all you have to do is pass the variable names as arguments in order.

It's easy to understand if you calm down and try a few of them yourself.

You can specify the display digit and right-justified and left-justified.

%10s //Prepare for 10 digits and right justify
%-10s //Prepare for 10 digits and left justify
%10s //Prepare for 10 digits and right justify
%-10s //Prepare for 10 digits and left justify
%5.3f //Display the integer part with 5 digits and the decimal part with 3 digits

For the last% 5.3f, I feel that it doesn't make much sense to specify the integer part. .. ..

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 integer part exceeds the specified number of digits, it is displayed as it is. Only a few have changed.

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

Recommended Posts

[Java] Output by specifying the format with printf% s,% d,% f [Format specifier]
Format of the log output by Tomcat itself in Tomcat 8
[Kotlin] Convert ZonedDateTime to String by specifying the format
Convert 2D array to csv format with Java 8 Stream API
Process the motion detected by the motion sensor HC-SR501 with Raspberry Pi 3 & Java