Java 中將數字或字串補齊固定長度(左補零、右補空格等)是常見格式化需求。本文提供三種主流實現方式:NumberFormat、String.format 與 DecimalFormat,並附流水號遞增實戰範例。
import java.text.NumberFormat;
public class NumberFormatTest {
public static void main(String[] args) {
int i = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false); // 關閉分組分隔符(如逗號)
nf.setMaximumIntegerDigits(4); // 最大整數位
nf.setMinimumIntegerDigits(4); // 最小整數位(不足左補零)
System.out.println(nf.format(i)); // 輸出:0001
}
}
適用場景: 純數字格式化,需關閉分組且精確控制整數位數。
public class TestStringFormat {
public static void main(String[] args) {
int num = 1;
// %04d:0=補零,4=總寬度,d=十進位整數
String str = String.format("%04d", num);
System.out.println(str); // 輸出:0001
// 右補空格:%-10s(負號表左對齊)
String padded = String.format("%-10s", "ABC");
System.out.println("[" + padded + "]"); // [ABC ]
}
}
格式化符號速查:
| 格式 | 說明 | 範例輸出 |
|---|---|---|
| %0nd | 左補零至 n 位整數 | %05d → 00042 |
| %ns | 右補空格至 n 寬度 | %5s → " abc" |
| %-ns | 左對齊(右補空格) | %-5s → "abc " |
| %0n.f | 浮點數左補零 | %06.2f → 003.14 |
import java.text.DecimalFormat;
public class SerialNumberUtil {
private static final String PATTERN = "0000"; // 固定 4 位
/** 流水號遞增並格式化 */
public static String nextSerial(String current) {
int next = Integer.parseInt(current) + 1;
DecimalFormat df = new DecimalFormat(PATTERN);
return df.format(next);
}
public static void main(String[] args) {
System.out.println(nextSerial("0001")); // 0002
System.out.println(nextSerial("0099")); // 0100
System.out.println(nextSerial("0999")); // 1000
}
}
DecimalFormat 模式符號:
0:必須顯示的數字位,不足補零#:可選數字位,不足不補零,:分組分隔符(如千分位).:小數點| 方法 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|
| NumberFormat | 標準 API、Locale 敏感 | 設定繁瑣、僅限數字 | 需國際化數字格式化 |
| String.format | 語法簡潔、支援字串/數字/日期 | 編譯期不檢查格式字串 | 通用首選、快速開發 |
| DecimalFormat | 模式靈活、可解析回數字 | 物件非執行緒安全 | 固定模式流水號、報表格式化 |
DecimalFormat 非執行緒安全,多執行緒環境請用 ThreadLocal 或每次新建實例。%04d 會保留負號(如 -001),若需特殊處理請先判斷符號。DecimalFormat 實例或改用 String.format(內部已優化)。