2010-04-24 41 views

回答

29

试试这个:

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

每次它被称为一个新的formater实例我创建。所以我不得不承认,大量的数据会导致大的内存问题。 – 2017-09-25 13:23:54

10

您还可以使用类DecimalFormat,像这样:

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

这也适用于一个格式字符串

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

但是其他的例子要容易得多。

3

又一种方式。 ;)

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

-1 => 99999999(九补)

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,尽管缓慢的解决方案:-)。尽管如此, – 2010-04-24 22:29:59

+1

不适用于底片。 – polygenelubricants 2010-04-25 05:53:16

+0

您可能会发现它不像其他解决方案那么慢,并且行为未定义为否定。就像其他解决方案一样,将会有一个非DDDDDDDD,其中D是一个数字,输出负数。 – 2010-04-25 12:00:06

0

如果您需要解析字符串,或支持国际化考虑延长

java.text.Format 

对象。使用其他答案来帮助你获得格式。

1

如果你只需要打印出来,这是一个较短的版本:

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

如果谷歌番石榴是一个选项:

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

或者阿帕奇共享郎咸平:

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