> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/programming-language/java/chang-yong-api/ge-shi-hua-shu-chu.md).

# 格式化输出

### System.out.printf()

Java中提供了`System.out.printf()`格式化输出：

**格式化模板的语法:**

```
%[argument_index$][flags][width][.precision]conversion
```

**参数解释:**

* conversion:占位符!
* argument\_index$:变量的索引!
* width:变量所占的宽度!
* flags:标记位,只要设置了width,默认是右对齐 ,如果将flag设置成-,则代表左对齐
* .precision:小数点的精度

`%conversion`常见的组合`[占位符!]*`

* %s 代表字符串
* %d 代表整数.
* %b 代表boolean类型
* %f 代表小数

> 注意%s可以接受任何类型的数据，并且占位符和变量的类型以及位置要一一对应!

具体产看Formatter类的API。

```java
String name = "Feathers";
int age = 22;
float salary = 15000.0F;
System.out.printf("我的名字叫%s,我今年%d岁了,月薪为%f\n", name, age, salary);

// s可以接收任何类型
System.out.printf("我的名字叫%s,我今年%s岁了,月薪为%s\n", name, age, salary);

//  %[argument_index$]conversion  参数索引  不推荐使用
System.out.printf("我的名字叫%2$s,我今年%1$s岁了,月薪为%3$s\n", age, name, salary );

// 改变参数的宽度，如果小于原始宽度，则无效
System.out.printf("我的名字叫%10s,我今年%5s岁了,月薪为%1s\n", name, age, salary);

// 当改变了参数的宽度，有可能多出一片空白，此时默认会右对齐，我们可以使用这个方法使其左对齐
System.out.printf("我的名字叫%10s,我今年%-5s岁了,月薪为%1s\n", name, age, salary);

// 限定小数的位数
System.out.printf("我的名字叫%s,我今年%d岁了,月薪为%5.2f\n", name, age, salary);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yangsx95.gitbook.io/notes/programming-language/java/chang-yong-api/ge-shi-hua-shu-chu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
