【问题标题】:How do I add left-padded zeros to a number in Java? [duplicate]如何在 Java 中将左填充零添加到数字中? [复制]
【发布时间】:2011-02-11 21:39:57
【问题描述】:

我有一个整数 100,如何将其格式化为类似于 00000100(总是 8 位长)?

【问题讨论】:

  • '8 digits'(而不是'8 numbers')会更正确

标签: java string-formatting


【解决方案1】:

如果 Google Guava 是一个选项:

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

或者 Apache Commons Lang:

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

【讨论】:

    【解决方案2】:

    另一种方式。 ;)

    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 为广告素材,虽然解决方案很慢 :-)。
    • 但不适用于底片。
    • 您可能会发现它不像其他解决方案那样慢,并且该行为未针对负数定义。就像其他解决方案一样,会有一个非 DDDDDDDD,其中 D 是一个数字,输出为负数。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      如果你需要解析这个字符串或者支持 i18n 考虑扩展

      java.text.Format 
      

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

      【讨论】:

        【解决方案5】:

        这也有效:

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

        但其他示例要容易得多。

        【讨论】:

          【解决方案6】:

          String.format 使用 格式字符串,描述为 here

          【讨论】:

            【解决方案7】:

            你也可以使用DecimalFormat这个类,像这样:

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

            【讨论】:

              【解决方案8】:

              试试这个:

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

              【讨论】:

              • 每次调用它都会创建一个新的格式化程序实例。所以我不得不承认,使用大量数据会导致大内存问题。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2014-03-16
              • 1970-01-01
              • 2014-10-24
              • 2014-12-10
              • 2016-07-24
              • 2010-10-03
              • 2019-11-21
              相关资源
              最近更新 更多