2010-04-24 5 views

Répondre

29

Essayez ceci:

String formattedNumber = String.format("%08d", number); 
+0

Chaque fois qu'on l'appelle une nouvelle instance formater i s créé. Je dois donc admettre qu'avec de grandes quantités de données, cela peut causer de gros problèmes de mémoire. –

10

Vous pouvez également utiliser la classe DecimalFormat, comme ceci:

NumberFormat formatter = new DecimalFormat("00000000"); 
System.out.println(formatter.format(100)); // 00000100 
2

String.format utilise une chaîne de format qui est décrit here

0

Cela fonctionne aussi :

int i = 53; 
String spaceHolder = "00000000"; 
String intString = String.valueOf(i); 
String string = spaceHolder.substring(intString.lenght()).contract(intString); 

Mais les autres exemples sont beaucoup plus faciles.

3

Encore une autre façon. ;)

int x = ... 
String text = (""+(500000000 + x)).substring(1); 

-1 => 99999999 (nines complémentaires)

import java.util.concurrent.Callable; 
/* Prints. 
String.format("%08d"): Time per call 3822 
(""+(500000000+x)).substring(1): Time per call 593 
Space holder: Time per call 730 
*/ 
public class StringTimer { 
    public static void time(String description, Callable<String> test) { 
     try { 
      // warmup 
      for(int i=0;i<10*1000;i++) 
       test.call(); 
      long start = System.nanoTime(); 
      for(int i=0;i<100*1000;i++) 
       test.call(); 
      long time = System.nanoTime() - start; 
      System.out.printf("%s: Time per call %d%n", description, time/100/1000); 
     } catch (Exception e) { 
      System.out.println(description+" failed"); 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String... args) { 
     time("String.format(\"%08d\")", new Callable<String>() { 
      int i =0; 
      public String call() throws Exception { 
       return String.format("%08d", i++); 
      } 
     }); 
     time("(\"\"+(500000000+x)).substring(1)", new Callable<String>() { 
      int i =0; 
      public String call() throws Exception { 
       return (""+(500000000+(i++))).substring(1); 
      } 
     }); 
     time("Space holder", new Callable<String>() { 
      int i =0; 
      public String call() throws Exception { 
       String spaceHolder = "00000000"; 
       String intString = String.valueOf(i++); 
       return spaceHolder.substring(intString.length()).concat(intString); 
      } 
     }); 
    } 
} 
+1

+1 pour la solution créative, mais lente :-). –

+1

Ne fonctionne pas avec des négatifs, cependant. – polygenelubricants

+0

Vous ne le trouverez peut-être pas aussi lent que les autres solutions, et le comportement n'est pas défini pour les négatifs. Tout comme les autres solutions, il y aura un non DDDDDDDD, où D est un chiffre, sortie pour les nombres négatifs. –

0

Si vous avez besoin pour analyser cette chaîne et ou support i18n envisager d'étendre la

java.text.Format 
objet

. Utilisez les autres réponses pour vous aider à obtenir le format.

1

Si vous avez juste besoin de l'imprimer, ceci est une version plus courte:

System.out.printf("%08d\n", number); 
2

Si Google Goyave est une option:

String output = Strings.padStart("" + 100, 8, '0'); 

Alternativement Apache Commons Lang:

String output = StringUtils.leftPad("" + 100, 8, "0"); 
Questions connexes