java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java String.format()

Java 格式化输出String.format() 示例解析

作者:Ahuuua

String.format() 是Java中非常强大的工具,掌握它可以让你在处理字符串输出时事半功倍,本文给大家介绍Java格式化输出String.format()的相关操作,感兴趣的朋友跟随小编一起看看吧

一、基本语法与结构

1.1 核心语法

// 基础语法
String formatted = String.format("格式字符串", 参数1, 参数2, ...);
// 等价写法(推荐)
String formatted = "格式字符串".formatted(参数1, 参数2, ...); // Java 15+
System.out.printf("格式字符串", 参数1, 参数2, ...); // 直接打印

1.2 你的示例解析

double i = 3.1415926;
System.out.println(String.format("%.3f", i));  // 输出: 3.142

二、格式说明符详解

格式说明符的完整结构:

%[参数索引$][标志][宽度][.精度]转换类型

2.1 转换类型(必需)

转换符适用类型说明示例
%d整数类型十进制整数"%d", 42"42"
%f浮点类型十进制浮点数"%.2f", 3.14159"3.14"
%s任意对象字符串"%s", "hello""hello"
%c字符Unicode字符"%c", 65"A"
%b布尔值true/false"%b", true"true"
%x整数十六进制"%x", 255"ff"
%o整数八进制"%o", 8"10"
%e浮点数科学计数法"%e", 1000.0"1.000000e+03"
%%-百分号本身"折扣: %d%%", 20"折扣: 20%"

2.2 宽度与精度

// 宽度:最小字符数(右对齐)
String.format("%5d", 42);     // "   42" (前面3个空格)
String.format("%-5d", 42);    // "42   " (左对齐,后面3个空格)
// 精度:对于浮点数控制小数位
String.format("%.2f", 3.14159);  // "3.14"
String.format("%.3f", 1.5);      // "1.500" (补零)
// 宽度和精度组合
String.format("%8.2f", 123.456); // "  123.46" (总宽8,2位小数)

2.3 标志(Flags)

标志作用示例
-左对齐"%-10s", "hi""hi "
+显示正负号"%+d", 42"+42"
0用零填充"%05d", 42"00042"
,千位分隔符"%,d", 1000000"1,000,000"
正数前加空格"% d", 42" 42"
(负数用括号"% (d", -42"(42)"

三、实际应用示例

3.1 数字格式化

// 金融金额格式化
double price = 2999.99;
String.format("价格: ¥%,.2f", price);  // "价格: ¥2,999.99"
// 百分比显示
double rate = 0.856;
String.format("成功率: %.1f%%", rate * 100);  // "成功率: 85.6%"
// 固定宽度表格数据
System.out.printf("%-10s %8s %8s%n", "商品", "单价", "数量");
System.out.printf("%-10s %8.2f %8d%n", "手机", 2999.99, 3);
System.out.printf("%-10s %8.2f %8d%n", "电脑", 5999.50, 1);

输出:

商品           单价      数量
手机         2999.99        3
电脑         5999.50        1

3.2 字符串格式化

// 固定宽度对齐
String.format("|%-20s|", "左对齐");  // "|左对齐               |"
String.format("|%20s|", "右对齐");   // "|               右对齐|"
// 截断字符串
String.format("%.5s", "Hello World");  // "Hello"
// 多参数格式化
String name = "张三";
int age = 25;
double score = 89.5;
String.format("学生: %s, 年龄: %d, 分数: %.1f", name, age, score);
// "学生: 张三, 年龄: 25, 分数: 89.5"

3.3 日期时间格式化

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime now = LocalDateTime.now();
// 方式1:使用DateTimeFormatter(推荐)
String formatted1 = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 方式2:使用String.format
String formatted2 = String.format("%tF %tT", now, now);  // "2024-01-15 14:30:25"

常用日期格式符:

Date date = new Date();
String.format("%tY-%tm-%td", date, date, date);  // "2024-01-15"
String.format("%tH:%tM:%tS", date, date, date);  // "14:30:25"
String.format("%tA", date);                      // "星期一" (中文环境)

四、参数索引与重用

4.1 参数索引(1$表示第一个参数)

// 重用参数
String.format("%1$s的分数是%2$d,%1$s的年龄是%3$d", 
              "张三", 95, 20);
// "张三的分数是95,张三的年龄是20"
// 改变参数顺序
String.format("%3$s %2$s %1$s", "A", "B", "C");  // "C B A"

4.2 复杂示例:格式化表格

public class TableFormatter {
    public static void main(String[] args) {
        Object[][] data = {
            {"商品A", 29.99, 150},
            {"商品B", 159.50, 42},
            {"商品C", 9.99, 1000}
        };
        System.out.println("=".repeat(40));
        System.out.printf("%-15s %10s %10s%n", "商品名称", "单价", "库存");
        System.out.println("-".repeat(40));
        for (Object[] row : data) {
            System.out.printf("%-15s %10.2f %10d%n", 
                row[0], row[1], row[2]);
        }
        System.out.println("=".repeat(40));
    }
}

输出:

========================================
商品名称                单价        库存
----------------------------------------
商品A                  29.99        150
商品B                 159.50         42
商品C                   9.99       1000
========================================

五、常见问题与解决方案

5.1 精度问题(浮点数)

// 问题:浮点数精度误差
double d = 0.1 + 0.2;  // 实际上是 0.30000000000000004
String.format("%f", d);  // "0.300000"
// 解决方案1:使用BigDecimal
import java.math.BigDecimal;
BigDecimal bd = new BigDecimal("0.1").add(new BigDecimal("0.2"));
String.format("%.2f", bd);  // "0.30"
// 解决方案2:使用DecimalFormat
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.##");
df.format(d);  // "0.3"

5.2 本地化支持

import java.util.Locale;
// 默认本地化
String.format(Locale.getDefault(), "%,.2f", 1234.56);
// 特定本地化(如美国)
String us = String.format(Locale.US, "%,.2f", 1234.56);  // "1,234.56"
// 特定本地化(如德国)
String de = String.format(Locale.GERMANY, "%,.2f", 1234.56);  // "1.234,56"
// 货币格式化
import java.text.NumberFormat;
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
nf.format(1234.56);  // "¥1,234.56"

5.3 性能优化

// 大量格式化时重用Formatter
import java.util.Formatter;
StringBuilder sb = new StringBuilder();
try (Formatter formatter = new Formatter(sb)) {
    for (int i = 0; i < 10000; i++) {
        formatter.format("第%d行: %.2f%n", i, Math.random());
    }
}
String result = sb.toString();

六、实用技巧汇总

6.1 快速格式化方法

// Java 15+ 的便捷方法
String result = "姓名: %s, 分数: %.1f".formatted("李四", 95.5);
// 链式调用
String message = String.format("%s%n%s%n", "标题", "-".repeat(20))
                   + String.format("值: %.2f", 123.456);

6.2 自定义格式化

// 自定义对象格式化
class Product {
    String name;
    double price;
    @Override
    public String toString() {
        return String.format("商品[%s] 价格:¥%.2f", name, price);
    }
}
Product p = new Product();
p.name = "手机"; p.price = 2999.99;
String.format("%s", p);  // "商品[手机] 价格:¥2999.99"

6.3 常见模式模板

public class FormatPatterns {
    // 文件名序号格式化
    public static String formatFileIndex(int index) {
        return String.format("file_%04d.txt", index);  // file_0001.txt
    }
    // 时间间隔格式化
    public static String formatDuration(long millis) {
        long hours = millis / 3600000;
        long minutes = (millis % 3600000) / 60000;
        long seconds = (millis % 60000) / 1000;
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    // 进度条显示
    public static String formatProgress(double current, double total) {
        double percent = (current / total) * 100;
        return String.format("[%-50s] %.1f%%", 
            "=".repeat((int)(percent / 2)), percent);
    }
}

七、总结速查表

需求格式字符串示例
保留2位小数"%.2f"3.14159"3.14"
宽度10,右对齐"%10s""test"" test"
宽度10,左对齐"%-10s""test""test "
补零到5位"%05d"42"00042"
千位分隔符"%,d"1000000"1,000,000"
十六进制"%x"255"ff"
科学计数法"%e"1000"1.000000e+03"
多参数重用"%1$s %1$s""A", "B""A A"
日期时间"%tF %tT""2024-01-15 14:30:25"

最佳实践建议

  1. 明确需求:先确定需要什么格式(小数位、对齐、千分位等)
  2. 测试边界:测试0、负数、大数值等特殊情况
  3. 考虑本地化:如果是国际化应用,使用Locale参数
  4. 性能考虑:大量格式化时考虑使用StringBuilder或Formatter
  5. 可读性优先:复杂的格式化考虑拆分成多行

String.format() 是Java中非常强大的工具,掌握它可以让你在处理字符串输出时事半功倍。从简单的数字格式化到复杂的报表生成,这个工具都能胜任。

到此这篇关于Java 格式化输出String.format() 详解的文章就介绍到这了,更多相关Java String.format() 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文