87. Java 数字和字符串 - 数字格式化与打印输出

79 阅读2分钟

87. Java 数字和字符串 - 数字格式化与打印输出

1. 介绍

在 Java 中,我们可以使用 printprintln 方法进行基本的输出,而 printfformat 方法可以提供更强大的格式化控制,使输出更加整齐、易读。本文将详细介绍 Java 的格式化输出方法,包括基本语法、常见格式说明符以及示例演示。


2. Printf Format 方法

Java 提供了 printfformat 方法,它们在 PrintStream 类(System.outPrintStream 对象)中定义,语法如下:

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 的 printfformat 方法支持多种格式说明符,常见格式如下:

常见转换符

转换符说明
%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