如何在 Java 中向数字添加左填充零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2705096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:03:51  来源:igfitidea点击:

How do I add left-padded zeros to a number in Java?

javastring-formatting

提问by Stig Christian

I have an integer 100, how do I format it to look like 00000100(always 8 digits long)?

我有一个整数100,如何将它格式化为看起来像00000100(总是 8 位数字)?

采纳答案by Andrew Hare

Try this:

尝试这个:

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

回答by Jo?o Silva

You can also use the class DecimalFormat, like so:

您还可以使用 class DecimalFormat,如下所示:

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

回答by stacker

String.formatuses a format stringwhich is described here

String.format使用这里描述的格式字符串

回答by Martijn Courteaux

This also works:

这也有效:

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

But the other examples are much easier.

但其他示例要容易得多。

回答by Peter Lawrey

Yet another way. ;)

还是另一种方式。;)

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

-1 => 99999999 (nines complement)

-1 => 99999999(9 的补码)

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);
            }
        });
    }
}

回答by Adam Gent

If you need to parse this string and or support i18n consider extending the

如果您需要解析此字符串和/或支持 i18n,请考虑扩展

java.text.Format 

object. Use the other answers to help you get the format.

目的。使用其他答案来帮助您获得格式。

回答by Denis Tulskiy

If you just need to print it out, this is a shorter version:

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

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

回答by Dag

If Google Guava is an Option:

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

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

Alternatively Apache Commons Lang:

或者 Apache Commons Lang:

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