我怎么能在左边用0填充一个整数呢?

时间:2022-02-13 21:34:03

How do you left pad an int with zeros in java when converting to a string?

在转换为字符串时,如何在java中以0作为0 ?

I'm basically looking to pad out integers up to 9999 with the leading zeros (e.g. 1 = "0001").

我基本上是想用前导零(例如,1 = "0001")来填充整数到9999。

12 个解决方案

#1


1415  

Use java.lang.String.format(String,Object...) like this:

使用java.lang.String.format(字符串、对象…)是这样的:

String.format("%05d", yournumber);

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

对于长度为5的零填充。对于十六进制输出,将d替换为“%05x”中的x。

The full formatting options are documented as part of java.util.Formatter.

完整的格式化选项被记录为java.util.Formatter的一部分。

#2


97  

If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

如果您出于任何原因使用前1.5 Java,那么可以尝试使用Apache Commons Lang方法。

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')

#3


56  

Let's say you want to print 11 as 011

假设你想打印11。

You could use a formatter: "%03d".

您可以使用格式化程序:“%03d”。

我怎么能在左边用0填充一个整数呢?

You can use this formatter like this:

你可以使用这样的格式化程序:

int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);

Alternatively, some java methods directly support these formatters:

或者,一些java方法直接支持这些格式化程序:

System.out.printf("%03d", a);

#4


26  

Found this example... Will test...

发现这个例子…将测试……

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Tested this and:

测试这个:

String.format("%05d",number);

Both work, for my purposes I think String.Format is better and more succinct.

这两项工作,我认为是字符串。格式更好,更简洁。

#5


13  

If performance is important in your case you could do it yourself with less overhead compared to the String.format function:

如果性能在您的情况下很重要,那么您可以使用比字符串更少的开销来完成它。格式功能:

/**
 * @param in The integer value
 * @param fill The number of digits to fill
 * @return The given value left padded with the given number of digits
 */
public static String lPadZero(int in, int fill){

    boolean negative = false;
    int value, len = 0;

    if(in >= 0){
        value = in;
    } else {
        negative = true;
        value = - in;
        in = - in;
        len ++;
    }

    if(value == 0){
        len = 1;
    } else{         
        for(; value != 0; len ++){
            value /= 10;
        }
    }

    StringBuilder sb = new StringBuilder();

    if(negative){
        sb.append('-');
    }

    for(int i = fill; i > len; i--){
        sb.append('0');
    }

    sb.append(in);

    return sb.toString();       
}

Performance

性能

public static void main(String[] args) {
    Random rdm;
    long start; 

    // Using own function
    rdm = new Random(0);
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        lPadZero(rdm.nextInt(20000) - 10000, 4);
    }
    System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");

    // Using String.format
    rdm = new Random(0);        
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        String.format("%04d", rdm.nextInt(20000) - 10000);
    }
    System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}

Result

结果

Own function: 1697ms

的功能:1697 ms

String.format: 38134ms

字符串。格式:38134毫秒

#6


13  

You can use Google Guava:

你可以使用谷歌番石榴:

Maven:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

示例代码:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

注意:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Guava是一个非常有用的库,它还提供了许多与集合、缓存、功能习惯用法、并发性、字符串、原语、范围、IO、哈希、EventBus等相关的特性。

Ref: GuavaExplained

裁判:GuavaExplained

#7


2  

Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.

虽然上面的许多方法都很好,但是有时候我们需要格式化整数和浮点数。我们可以使用这个,特别是当我们需要在左边加上特定数目的零和十进制数时。

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  

#8


2  

int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.

如果您想要将格式化文本直接打印到屏幕上。

#9


0  

Check my code that will work for integer and String.

检查我的代码是否适用于整数和字符串。

Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

假设我们的第一个数字是2。我们要把0加到这上面所以最后的长度是4。您可以使用以下代码。

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

#10


0  

You need to use a Formatter, following code uses NumberFormat

您需要使用格式化程序,下面的代码使用NumberFormat。

    int inputNo = 1;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumIntegerDigits(4);
    nf.setMinimumIntegerDigits(4);
    nf.setGroupingUsed(false);

    System.out.println("Formatted Integer : " + nf.format(inputNo));

Output: 0001

输出:0001

#11


-2  

public static String zeroPad(long number, int width) {
   long wrapAt = (long)Math.pow(10, width);
   return String.valueOf(number % wrapAt + wrapAt).substring(1);
}

The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.

这种方法的唯一问题是,它会让你戴上你的思维帽去弄清楚它是如何工作的。

#12


-5  

No packages needed:

不需要包:

String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;

This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

这将把字符串填充到三个字符,并且很容易在4或5个字符中添加一个部分。我知道这不是完美的解决方案(特别是如果你想要一个大的填充字符串),但是我喜欢它。

#1


1415  

Use java.lang.String.format(String,Object...) like this:

使用java.lang.String.format(字符串、对象…)是这样的:

String.format("%05d", yournumber);

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

对于长度为5的零填充。对于十六进制输出,将d替换为“%05x”中的x。

The full formatting options are documented as part of java.util.Formatter.

完整的格式化选项被记录为java.util.Formatter的一部分。

#2


97  

If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

如果您出于任何原因使用前1.5 Java,那么可以尝试使用Apache Commons Lang方法。

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')

#3


56  

Let's say you want to print 11 as 011

假设你想打印11。

You could use a formatter: "%03d".

您可以使用格式化程序:“%03d”。

我怎么能在左边用0填充一个整数呢?

You can use this formatter like this:

你可以使用这样的格式化程序:

int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);

Alternatively, some java methods directly support these formatters:

或者,一些java方法直接支持这些格式化程序:

System.out.printf("%03d", a);

#4


26  

Found this example... Will test...

发现这个例子…将测试……

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Tested this and:

测试这个:

String.format("%05d",number);

Both work, for my purposes I think String.Format is better and more succinct.

这两项工作,我认为是字符串。格式更好,更简洁。

#5


13  

If performance is important in your case you could do it yourself with less overhead compared to the String.format function:

如果性能在您的情况下很重要,那么您可以使用比字符串更少的开销来完成它。格式功能:

/**
 * @param in The integer value
 * @param fill The number of digits to fill
 * @return The given value left padded with the given number of digits
 */
public static String lPadZero(int in, int fill){

    boolean negative = false;
    int value, len = 0;

    if(in >= 0){
        value = in;
    } else {
        negative = true;
        value = - in;
        in = - in;
        len ++;
    }

    if(value == 0){
        len = 1;
    } else{         
        for(; value != 0; len ++){
            value /= 10;
        }
    }

    StringBuilder sb = new StringBuilder();

    if(negative){
        sb.append('-');
    }

    for(int i = fill; i > len; i--){
        sb.append('0');
    }

    sb.append(in);

    return sb.toString();       
}

Performance

性能

public static void main(String[] args) {
    Random rdm;
    long start; 

    // Using own function
    rdm = new Random(0);
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        lPadZero(rdm.nextInt(20000) - 10000, 4);
    }
    System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");

    // Using String.format
    rdm = new Random(0);        
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        String.format("%04d", rdm.nextInt(20000) - 10000);
    }
    System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}

Result

结果

Own function: 1697ms

的功能:1697 ms

String.format: 38134ms

字符串。格式:38134毫秒

#6


13  

You can use Google Guava:

你可以使用谷歌番石榴:

Maven:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

示例代码:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

注意:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Guava是一个非常有用的库,它还提供了许多与集合、缓存、功能习惯用法、并发性、字符串、原语、范围、IO、哈希、EventBus等相关的特性。

Ref: GuavaExplained

裁判:GuavaExplained

#7


2  

Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.

虽然上面的许多方法都很好,但是有时候我们需要格式化整数和浮点数。我们可以使用这个,特别是当我们需要在左边加上特定数目的零和十进制数时。

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  

#8


2  

int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.

如果您想要将格式化文本直接打印到屏幕上。

#9


0  

Check my code that will work for integer and String.

检查我的代码是否适用于整数和字符串。

Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

假设我们的第一个数字是2。我们要把0加到这上面所以最后的长度是4。您可以使用以下代码。

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

#10


0  

You need to use a Formatter, following code uses NumberFormat

您需要使用格式化程序,下面的代码使用NumberFormat。

    int inputNo = 1;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumIntegerDigits(4);
    nf.setMinimumIntegerDigits(4);
    nf.setGroupingUsed(false);

    System.out.println("Formatted Integer : " + nf.format(inputNo));

Output: 0001

输出:0001

#11


-2  

public static String zeroPad(long number, int width) {
   long wrapAt = (long)Math.pow(10, width);
   return String.valueOf(number % wrapAt + wrapAt).substring(1);
}

The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.

这种方法的唯一问题是,它会让你戴上你的思维帽去弄清楚它是如何工作的。

#12


-5  

No packages needed:

不需要包:

String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;

This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

这将把字符串填充到三个字符,并且很容易在4或5个字符中添加一个部分。我知道这不是完美的解决方案(特别是如果你想要一个大的填充字符串),但是我喜欢它。