You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java String.format中通过参数指定整数的特定格式化宽度

问题解决方法

你遇到的问题可以通过两种方式实现动态宽度的整数格式化:

核心原理

Java的String.format依赖java.util.Formatter语法,支持两种动态传宽度的方案,同时要注意Java中没有%i整数格式符,统一用%d格式化整数。


方案1:用*占位动态宽度(更推荐)

格式说明符中的宽度位置写*时,会自动从入参列表读取下一个int值作为宽度,代码实现如下:

import java.io.PrintWriter;

public class SomeFormats {

    public static void main (String[]args) {
        PrintWriter out = new PrintWriter (System.out);
        // 输出的10会前置28个空格,总长度为30
        System.out.println(prettyInt(10, 30));
        out.flush();
    }

    public static String prettyInt(int n, int width) {
        // 第一个入参width对应*的位置作为格式化宽度,第二个入参n对应%d的格式化目标
        return String.format("%*d", width, n);
    }
}

如果需要左对齐展示,只需要在格式符前加-即可,格式串写为%-*d。


方案2:提前拼接格式字符串

先把宽度变量拼到格式串中,再传入要格式化的整数即可:

public static String prettyInt(int n, int width) {
    // 拼接后得到类似"%30d"的固定格式串
    String formatPattern = "%" + width + "d";
    return String.format(formatPattern, n);
}

内容的提问来源于stack exchange,提问作者Fl4chz4nge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:45:00