首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中,如何将左填充的零添加到数字?

在Java中,如何将左填充的零添加到数字?
EN

Stack Overflow用户
提问于 2010-04-24 23:54:36
回答 8查看 23.7K关注 0票数 16

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

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2010-04-24 23:56:01

试试这个:

代码语言:javascript
复制
String formattedNumber = String.format("%08d", number);
票数 33
EN

Stack Overflow用户

发布于 2010-04-25 00:03:55

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

代码语言:javascript
复制
NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100
票数 11
EN

Stack Overflow用户

发布于 2010-04-25 04:50:35

还有另一种方式。;)

代码语言:javascript
复制
int x = ...
String text = (""+(500000000 + x)).substring(1);

-1 \f25 => 99999999 -1\f6(9补码)

代码语言:javascript
复制
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);
            }
        });
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2705096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档