Java String字符串補0或空格


Java代碼   收藏代碼
  1. package cn.com.songjy;  
  2.   
  3. import java.text.NumberFormat;  
  4. //Java 中給數字左邊補0  
  5. public class NumberFormatTest {  
  6.   
  7.     public static void main(String[] args) {  
  8.         // 待測試數據  
  9.         int i = 1;  
  10.         // 得到一個NumberFormat的實例  
  11.         NumberFormat nf = NumberFormat.getInstance();  
  12.         // 設置是否使用分組  
  13.         nf.setGroupingUsed(false);  
  14.         // 設置最大整數位數  
  15.         nf.setMaximumIntegerDigits(4);  
  16.         // 設置最小整數位數  
  17.         nf.setMinimumIntegerDigits(4);  
  18.         // 輸出測試語句  
  19.         System.out.println(nf.format(i));  
  20.     }  
  21. }  



Java代碼   收藏代碼
  1. /**   
  2.  * Java里數字轉字符串前面自動補0的實現。   
  3.  *     
  4.  */    
  5. public class TestStringFormat {     
  6.   public static void main(String[] args) {     
  7.     int youNumber = 1;     
  8.     // 0 代表前面補充0     
  9.     // 4 代表長度為4     
  10.     // d 代表參數為正數型     
  11.     String str = String.format("%04d", youNumber);     
  12.     System.out.println(str); // 0001     
  13.   }     
  14. }    



Java代碼   收藏代碼
    1. //流水號加1后返回,流水號長度為4  
    2.     private static final String STR_FORMAT = "0000";   
    3.   
    4.     public static String haoAddOne_2(String liuShuiHao){  
    5.         Integer intHao = Integer.parseInt(liuShuiHao);  
    6.         intHao++;  
    7.         DecimalFormat df = new DecimalFormat(STR_FORMAT);  
    8.         return df.format(intHao);  
    9.     }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM