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

Spring Controller中整数转固定4位带前导零字符串的实现问题

实现int转固定4位带前导零字符串的方案

针对你需要把int类型id转成固定4位、不足补前导零字符串的需求,推荐这几种简单直接的实现方式:

1. 用String.format()(最简洁,Java自带无需额外依赖)

直接替换原转换代码,通过格式化字符串快速实现:

public ModelAndView showUserAppsByID(@PathVariable(name = "id") int id) {
   // %04d 规则:总长度4位,空位用0填充,d对应整数类型
   String emIDConvert = String.format("%04d", id);
   // ... 后续业务逻辑
}

输入3会得到"0003",输入43会得到"0043",完全匹配需求。

2. 用DecimalFormat(适合多处复用格式的场景)

如果这个格式化逻辑在项目里多次用到,可以把格式实例定义为静态常量,提升复用性:

// 定义为类的静态常量,避免重复创建实例
private static final DecimalFormat FOUR_DIGIT_FORMAT = new DecimalFormat("0000");

public ModelAndView showUserAppsByID(@PathVariable(name = "id") int id) {
   String emIDConvert = FOUR_DIGIT_FORMAT.format(id);
   // ... 后续业务逻辑
}

"0000"模式明确指定输出为4位数字,不足的位置自动补0。

3. 用StringUtils.leftPad()(依赖Apache Commons Lang工具类)

如果你的项目已经引入了Apache Commons Lang依赖,可借助工具类方法快速实现:

import org.apache.commons.lang3.StringUtils;

public ModelAndView showUserAppsByID(@PathVariable(name = "id") int id) {
   String emIDConvert = StringUtils.leftPad(Integer.toString(id), 4, '0');
   // ... 后续业务逻辑
}

该方法逻辑为:将id转成的原始字符串向左填充字符'0',直到总长度达到4位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:10:07