在 Java 中为数字添加前导零?

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

Add leading zeroes to number in Java?

java

提问by Nate Parsons

Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)

有没有更好的方法来获得这个结果?如果 num 的数字多于数字,则此函数将失败,并且我觉得它应该在库中的某个地方(例如 Integer.toString(x,"%3d") 或其他内容)

static String intToString(int num, int digits) {
    StringBuffer s = new StringBuffer(digits);
    int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; 
    for (int i = 0; i < zeroes; i++) {
        s.append(0);
    }
    return s.append(num).toString();
}

采纳答案by begray

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

String.format ( https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

在您的情况下,它将是:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3
  • 0 - 用零填充
  • 3 - 将宽度设置为 3

回答by Jason Coco

Since Java 1.5 you can use the String.formatmethod. For example, to do the same thing as your example:

从 Java 1.5 开始,您可以使用该String.format方法。例如,要执行与您的示例相同的操作:

String format = String.format("%%0%dd", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

在这种情况下,您将使用以数字指定的宽度创建格式字符串,然后将其直接应用于数字。此示例的格式转换如下:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05dwhich specifies an integer with a width of 5 printing leading zeroes. See the java docsfor String.formatfor more information on the conversion specifiers.

因此,如果数字等于 5,则格式字符串将变为%05d指定宽度为 5 的整数,打印前导零。请参阅Java文档String.format有关转换说明的更多信息。

回答by Elijah

Another option is to use DecimalFormatto format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

另一种选择是使用DecimalFormat来格式化数字字符串。如果您被困在 1.5 之前的世界中,那么这是另一种无需使用 String.format 即可完成这项工作的方法:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

回答by Madhu Subramanian

In case of your jdk version less than 1.5, following option can be used.

如果您的 jdk 版本低于 1.5,可以使用以下选项。

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

回答by Torin Rudeen

How about just:

怎么样:

public static String intToString(int num, int digits) {
    String output = Integer.toString(num);
    while (output.length() < digits) output = "0" + output;
    return output;
}