87. Java 数字和字符串 - 数字格式化与打印输出
1. 介绍
在 Java 中,我们可以使用 print、println 方法进行基本的输出,而 printf 和 format 方法可以提供更强大的格式化控制,使输出更加整齐、易读。本文将详细介绍 Java 的格式化输出方法,包括基本语法、常见格式说明符以及示例演示。
2. Printf 和 Format 方法
Java 提供了 printf 和 format 方法,它们在 PrintStream 类(System.out 是 PrintStream 对象)中定义,语法如下:
public PrintStream format(String format, Object... args)
其中:
format:格式化字符串,指定变量如何被格式化。args:要格式化的变量列表(可变参数)。
示例 1:基本格式化输出
int intVar = 10;
double floatVar = 3.14159;
String stringVar = "Java";
System.out.format("The value of the float variable is %f, while the value of the integer variable is %d, and the string is %s%n",
floatVar, intVar, stringVar);
输出:
The value of the float variable is 3.141590, while the value of the integer variable is 10, and the string is Java
✅ 注意:
%f格式化浮点数,%d格式化整数,%s格式化字符串。
示例 2:基本整数格式化
int i = 461012;
System.out.format("The value of i is: %d%n", i);
输出:
The value of i is: 461012
3. 格式说明符与标志
Java 的 printf 和 format 方法支持多种格式说明符,常见格式如下:
常见转换符
| 转换符 | 说明 |
|---|---|
%d | 十进制整数 |
%f | 浮点数 |
%s | 字符串 |
%n | 换行符(适应不同操作系统) |
%tB | 日期 - 月份全名(如 March) |
%tY | 日期 - 4 位数年份(如 2025) |
%tD | 日期格式(MM/dd/yy) |
常见标志
| 标志 | 说明 |
|---|---|
0 | 用零填充宽度不足的数值 |
+ | 总是显示正负号 |
, | 添加千位分隔符(如 1,000,000) |
- | 左对齐 |
.3 | 小数点后保留 3 位 |
10.3 | 总宽度 10,保留 3 位小数 |
4. 示例演示
示例 3:控制整数格式
long n = 461012;
System.out.format("%08d%n", n); // 8 位宽度,前导 0
System.out.format("%+8d%n", n); // 8 位宽度,显示正负号
System.out.format("%,8d%n", n); // 8 位宽度,带千分符
System.out.format("%+,8d%n", n); // 8 位宽度,带千分符和符号
输出:
00461012
+461012
461,012
+461,012
示例 4:控制浮点数格式
double pi = Math.PI;
System.out.format("%f%n", pi); // 默认 6 位小数
System.out.format("%.3f%n", pi); // 保留 3 位小数
System.out.format("%10.3f%n", pi); // 宽度 10,右对齐
System.out.format("%-10.3f%n", pi); // 宽度 10,左对齐
System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // 法国区域,逗号作小数点
输出:
3.141593
3.142
3.142
3.142
3,1416
示例 5:日期格式化
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // 月份全名、日期、年份
System.out.format("%tl:%tM %tp%n", c, c, c); // 12 小时制,分钟,am/pm
System.out.format("%tD%n", c); // MM/DD/YY
}
}
输出(示例):
March 23, 2025
2:34 am
03/23/25