首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 字串補零與補空格完整代碼範例

     編輯:Java 相關知識

Java 中將數字或字串補齊固定長度(左補零、右補空格等)是常見格式化需求。本文提供三種主流實現方式:NumberFormat、String.format 與 DecimalFormat,並附流水號遞增實戰範例。

方法一:NumberFormat(標準 API,適合數字右補零)

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
    }
}

適用場景: 純數字格式化,需關閉分組且精確控制整數位數。

方法二:String.format(最簡潔,推薦通用)

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

方法三:DecimalFormat(模式靈活,適合流水號)

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模式靈活、可解析回數字物件非執行緒安全固定模式流水號、報表格式化

注意事項

  1. 執行緒安全:DecimalFormat 非執行緒安全,多執行緒環境請用 ThreadLocal 或每次新建實例。
  2. 負數處理:%04d 會保留負號(如 -001),若需特殊處理請先判斷符號。
  3. 效能:高頻呼叫建議緩存 DecimalFormat 實例或改用 String.format(內部已優化)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved