Java 如何在左侧用零填充整数?

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

How can I pad an integer with zeros on the left?

javaformattingzero-pad

提问by Omar Kooheji

How do you left pad an intwith zeros when converting to a Stringin java?

在 java 中int转换为 a 时,如何用零填充 an String

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

我基本上希望9999用前导零填充整数(例如 1 = 0001)。

采纳答案by Yoni Roit

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

java.lang.String.format(String,Object...)像这样使用:

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

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

用于填充零为5的长度十六进制输出替换dx如在"%05x"

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

完整的格式选项记录为java.util.Formatter.

回答by Omar Kooheji

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.

两者都有效,就我的目的而言,我认为 String.Format 更好更简洁。

回答by Boris Pavlovi?

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')

回答by johncurrier

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.

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

回答by Deepak

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(",",""));  
 }    
}  

回答by Shashi

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

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

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

回答by das Keks

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

如果性能在您的情况下很重要,与String.format函数相比,您可以用更少的开销自己完成:

/**
 * @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

自带函数:1697ms

String.format:38134ms

字符串格式38134ms

回答by Fathah Rehman P

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。我们想给它加零,所以最终字符串的长度将为 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("
<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>
", "0")+number; } System.out.println(resultString);

回答by Tho

You can use Google Guava:

您可以使用谷歌番石榴

Maven:

马文:

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

Sample code:

示例代码:

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

Note:

笔记:

Guavais 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是非常有用的图书馆,还提供了很多这关系到功能CollectionsCachesFunctional idiomsConcurrencyStringsPrimitivesRangesIOHashingEventBus,等

Ref: GuavaExplained

参考:番石榴解释

回答by bvdb

Let's say you want to print 11as 011

假设您想打印11011

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

您可以使用格式化程序"%03d"

enter image description here

在此处输入图片说明

You can use this formatter like this:

您可以像这样使用此格式化程序:

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

Alternatively, some java methods directly support these formatters:

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

##代码##