如何在整数的左侧填充零?

发布于 2024-07-12 12:40:07 字数 135 浏览 5 评论 0原文

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

滥情稳全场 2024-07-19 12:40:08

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

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

用于长度为 5 的零填充。对于十六进制输出,请将dx“%05x” 中所示。

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

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

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

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

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

遇到 2024-07-19 12:40:08

假设您要将 11 打印为 011

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

输入图像描述这里

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

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

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

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

Let's say you want to print 11 as 011

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

enter image description here

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:

System.out.printf("%03d", a);
甜点 2024-07-19 12:40:08

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

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

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

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
过去的过去 2024-07-19 12:40:08

找到这个例子...将测试...

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));
    }
}

测试了这个并且:

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

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

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.

平定天下 2024-07-19 12:40:08

试试这个:

import java.text.DecimalFormat; 

DecimalFormat df = new DecimalFormat("0000");

String c = df.format(9);   // Output: 0009

String a = df.format(99);  // Output: 0099

String b = df.format(999); // Output: 0999

Try this one:

import java.text.DecimalFormat; 

DecimalFormat df = new DecimalFormat("0000");

String c = df.format(9);   // Output: 0009

String a = df.format(99);  // Output: 0099

String b = df.format(999); // Output: 0999
一身骄傲 2024-07-19 12:40:08

以下是如何在不使用 DecimalFormat 的情况下格式化字符串。

String.format("%02d", 9)

09

String.format("%03d", 19)

019

字符串.format("%04d", 119)

0119

Here is how you can format your string without using DecimalFormat.

String.format("%02d", 9)

09

String.format("%03d", 19)

019

String.format("%04d", 119)

0119

入画浅相思 2024-07-19 12:40:08

如果性能对您的情况很重要,您可以自己完成,与 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();       
}

性能

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

结果

自己函数: 1697ms

字符串格式: 38134ms

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

String.format: 38134ms

无妨# 2024-07-19 12:40:08

您可以使用 Google Guava

Maven:

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

示例代码:

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

注意:

Guava 是非常有用的库,它还提供了很多与 Collections相关的功能缓存函数惯用语并发字符串基元范围 >、IOHashingEventBus

参考:GuavaExplained

You can use Google Guava:

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

Ref: GuavaExplained

请你别敷衍 2024-07-19 12:40:08

虽然上面的许多方法都很好,但有时我们需要格式化整数和浮点数。 我们可以使用它,特别是当我们需要在十进制数的左侧和右侧填充特定数量的零时。

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

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(",",""));  
 }    
}  
何处潇湘 2024-07-19 12:40:08
int x = 1;
System.out.format("%05d",x);

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

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

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

行至春深 2024-07-19 12:40:08

您需要使用格式化程序,以下代码使用 数字格式

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

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

输出:0001

You need to use a Formatter, following code uses 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

蓝眼泪 2024-07-19 12:40:08

使用 DecimalFormat 类,如下所示:

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

输出: 0000811

Use the class DecimalFormat, like so:

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

OUTPUT : 0000811

塔塔猫 2024-07-19 12:40:08

在 Kotlin 中,您可以使用 format() 函数。

val minutes = 5
val strMinutes = "%02d".format(minutes)

其中,2是要显示的总位数(包括零)。

输出:05

In Kotlin, you can use format() function.

val minutes = 5
val strMinutes = "%02d".format(minutes)

where, 2 is the total number of digits you want to display(including zero).

Output: 05

吻风 2024-07-19 12:40:08

如果您使用的是 Java 15 及更高版本,

var minutes = 5
var strMinutes = "%02d".formatted(minutes)

其中 2 是您要显示的总位数(包括零)。

Output: 05

这使用了调用的字符串实例方法的formatted方法部分,其作用与静态String.format(str,x,y,z)相同

If you are on Java 15 and above,

var minutes = 5
var strMinutes = "%02d".formatted(minutes)

where, 2 is the total number of digits you want to display(including zero).

Output: 05

This uses formatted method part of instance method on Strings called which does the same as the static String.format(str,x,y,z)

手心的海 2024-07-19 12:40:08

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

假设我们的第一个数字是 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("\0", "0")+number;
    }        
    System.out.println(resultString);

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

    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);
活泼老夫 2024-07-19 12:40:08

您可以像这样在字符串中添加前导 0。 定义一个字符串,该字符串将是所需字符串的最大长度。 就我而言,我需要一个只有 9 个字符长的字符串。

String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);

输出:000602939

You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.

String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);

Output : 000602939

何以笙箫默 2024-07-19 12:40:08

使用这个简单的 Kotlin 扩展函数

fun Int.padWithZeros(): String {
   return this.toString().padStart(4, '0')
}

Use this simple Kotlin Extension function

fun Int.padWithZeros(): String {
   return this.toString().padStart(4, '0')
}
表情可笑 2024-07-19 12:40:08

不需要包:

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

这会将字符串填充为三个字符,并且很容易添加四个或五个字符的部分。 我知道这无论如何都不是完美的解决方案(特别是如果您想要一个大的填充字符串),但我喜欢它。

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.

半边脸i 2024-07-19 12:40:08

这是在整数左侧填充零的另一种方法。 您可以根据自己的方便增加零的数量。 添加了一项检查,以返回与负数或大于或等于配置的零的值相同的值。 您可以根据您的要求进一步修改。

/**
 * 
 * @author Dinesh.Lomte
 *
 */
public class AddLeadingZerosToNum {
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        
        System.out.println(getLeadingZerosToNum(0));
        System.out.println(getLeadingZerosToNum(7));
        System.out.println(getLeadingZerosToNum(13));
        System.out.println(getLeadingZerosToNum(713));
        System.out.println(getLeadingZerosToNum(7013));
        System.out.println(getLeadingZerosToNum(9999));
    }
    /**
     * 
     * @param num
     * @return
     */
    private static String getLeadingZerosToNum(int num) {
        // Initializing the string of zeros with required size
        String zeros = new String("0000");
        // Validating if num value is less then zero or if the length of number 
        // is greater then zeros configured to return the num value as is
        if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
            return String.valueOf(num);
        }
        // Returning zeros in case if value is zero.
        if (num == 0) {
            return zeros;
        }
        return new StringBuilder(zeros.substring(0, zeros.length() - 
                String.valueOf(num).length())).append(
                        String.valueOf(num)).toString();
    }
}

输入

0

7

13

713

7013

9999

输出

0000

0007

0013

7013

9999

Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.

/**
 * 
 * @author Dinesh.Lomte
 *
 */
public class AddLeadingZerosToNum {
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        
        System.out.println(getLeadingZerosToNum(0));
        System.out.println(getLeadingZerosToNum(7));
        System.out.println(getLeadingZerosToNum(13));
        System.out.println(getLeadingZerosToNum(713));
        System.out.println(getLeadingZerosToNum(7013));
        System.out.println(getLeadingZerosToNum(9999));
    }
    /**
     * 
     * @param num
     * @return
     */
    private static String getLeadingZerosToNum(int num) {
        // Initializing the string of zeros with required size
        String zeros = new String("0000");
        // Validating if num value is less then zero or if the length of number 
        // is greater then zeros configured to return the num value as is
        if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
            return String.valueOf(num);
        }
        // Returning zeros in case if value is zero.
        if (num == 0) {
            return zeros;
        }
        return new StringBuilder(zeros.substring(0, zeros.length() - 
                String.valueOf(num).length())).append(
                        String.valueOf(num)).toString();
    }
}

Input

0

7

13

713

7013

9999

Output

0000

0007

0013

7013

9999

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文