1. 程式人生 > >Java中數字前補零的方法,數字加減前補零函式

Java中數字前補零的方法,數字加減前補零函式

 
  1.  * 將元資料前補零,補後的總長度為指定的長度,以字串的形式返回

  2.  
  3.   * @param sourceDate

  4.  
  5.   * @param formatLength

  6.  
  7.   * @return 重組後的資料

  8.  
  9.   */

  10.  
  11.   public static String frontCompWithZore(int sourceDate,int formatLength)

  12.  
  13.   {

  14.  
  15.   /*

  16.  
  17.   * 0 指前面補充零

  18.  
  19.   * formatLength 字元總長度為 formatLength

  20.  
  21.   * d 代表為正數。

  22.  
  23.   */

  24.  
  25.   String newString = String.format("%0"+formatLength+"d", sourceDate);

  26.  
  27.   return newString;

  28.  
  29.   }

 

如:

 
  1. String newString = String.format("%02d", 5);

  2. System.out.println("newString === "+newString);


執行結果:

 

newString === 05