如何在 Java 中用前导空格格式化数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22541056/
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 16:22:00  来源:igfitidea点击:

How to format numbers with leading spaces in Java

javaformattingpaddingspace

提问by user3437460

I have the following Java codes to generate numbers padded by zeroes.

我有以下 Java 代码来生成用零填充的数字。

    DecimalFormat fmt = new DecimalFormat("000");
    for (int y=1; y<12; y++)
    {
        System.out.print(fmt.format(y) + " ");
    }

The output is as follows:

输出如下:

001 002 003 004 005 006 007 008 009 010 011

001 002 003 004 005 006 007 008 009 010 011

My question is: how do I generate numbers with padded spaces instead of leading zeroes?

我的问题是:如何生成带有填充空格而不是前导零的数字?

1 2 3 4 5 6 7 8 9 10 11

1 2 3 4 5 6 7 8 9 10 11

Note: I know there are several quesitons achieved in StackOverflow asking for padding spaces in String. I know how to do it with String. I am asking is it possible to format NUMBERSwith padded space?

注意:我知道在 StackOverflow 中有几个问题要求在 String 中填充空格。我知道如何用 String 做到这一点。我问是否可以用填充空间格式化NUMBERS

采纳答案by Raul Guiu

    for (int y=1; y<12; y++)
    {
        System.out.print(String.format("%1s", y));
    }

It will print Strings of length 4, so if y=1 it will print 3 spaces and 1, " 1", if y is 10 it will print 2 spaces and 10, " 10"

它将打印长度为 4 的字符串,因此如果 y=1 它将打印 3 个空格和 1, " 1",如果 y 是 10 它将打印 2 个空格和 10, " 10"

See the javadocs

请参阅 javadoc

回答by user176692

int i = 0;
while (i < 12) {
    System.out.printf("%4d", i);
    ++i;
}

The 4 is the width. You could also replace printf with format.

4 是宽度。您也可以用格式替换 printf 。