> 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);
```
