Location>code7788 >text

Output formatting in Java

Popularity:205 ℃/2025-02-13 16:26:45

In Java, output formatting is a very important function, especially in scenarios where precise control of the output format is required.

Here is a detailed explanation of the output part in the code:

Output in the original code:

("%.6f\n", l);

Detailed explanation:


It is a method used in Java to format output, similar to that in C/C++printf function.
It can format the output data according to the specified format string.
Format string %.6f
%.6fis a formatted placeholder that specifies the output format of floating point numbers. in:
% Indicates the beginning of the formatting placeholder.
.6It means that 6 digits are retained after the decimal point.
f Represents a floating-point number.

Output result:

("%.6f\n", l); Meaning:
Put variableslThe value of the value is formatted as a floating point, and the 6-digit number is retained after the decimal point, and the line break is output.

For example, ifl The value of the value is 2.12345678, and the output will be:

2.123457

Line breaks \n

\nis a newline character, used to break the line after output.
In Java, line breaks are represented in the same way as in C/C++.
Other formatting options:
If more flexible formatting is required, other formatting placeholders can be used, such as:

%.2f: Keep 2 decimal places.
%d: Output integer.
%s: Output string.
%e: Output floating point numbers using scientific notation.

Sample code:

public class Main {
    public static void main(String[] args) {
        double num = 123.456789;
        int integer = 123;
        String str = "Hello";

        // Floating point number, retaining 6 decimal places
        ("%.6f\n", num); // Output: 123.456789

        // Floating point number, retaining 2 decimal places
        ("%.2f\n", num); // Output: 123.46

        // Integer
        ("%d\n", integer); // Output: 123

        // String
        ("%s\n", str); // Output: Hello

        // Scientific Counting Method
        ("%e\n", num); // Output: 1.234568e+02
    }
 }

Output:

123.456789
123.46
123
Hello
1.234568e+02