In Java, use the printf method to align numeric output. The format specifier %n specifies the minimum field width and is padded with spaces. %0n is padded with zeros. %-n is left-aligned. Numbers are right-aligned by default.
Align output numbers in Java
In Java, you can use the printf
method to align Digital output. The printf
method uses a format string to specify the format of the output data.
Alignment format
The following format specifiers can be used to align numeric output:
n
: Specifies the minimum field width. If the number length is smaller than this width, it will be padded with spaces. n
: Same as %
n`, but padded with zeros. n
: left-aligned numbers, by default numbers are right-aligned. Sample Code
The following sample code demonstrates how to align numeric output:
<code class="java">// 对齐数字,最小字段宽度为 10,空格填充 System.out.printf("%10d", 1234); // 输出 " 1234" // 对齐数字,最小字段宽度为 10,零填充 System.out.printf("%010d", 1234); // 输出 "000001234" // 对齐数字,最小字段宽度为 10,左对齐 System.out.printf("%-10d", 1234); // 输出 "1234 "</code>
Note:
%n
The format specifier does not apply to floating point output. The above is the detailed content of How to align output numbers in java. For more information, please follow other related articles on the PHP Chinese website!