Home  >  Article  >  Java  >  How to align output numbers in java

How to align output numbers in java

下次还敢
下次还敢Original
2024-04-21 02:31:58933browse

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.

How to align output numbers in java

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.
  • %0n: 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:

  • If the number length exceeds the specified minimum field width, the number will be output according to its original length.
  • %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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn