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

1220

在Java中将int转换为String时,如何用零进行左侧填充?

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


2
没错,就是这样!我的错...我在手机上输入的。你也不需要使用"new String":Integer.toString(num+10000).subString(1)就可以了。 - Randyaa
Long.valueOf("00003400").toString(); Integer.valueOf("00003400").toString(); --->3400 - frekele
1
请参考以下链接中的解决方案和图表,以在Java中打印具有前导零的整数:https://dev59.com/YZTfa4cB1Zd3GeqPOkgl#35521965 - bvdb
如果num大于9999,那么使用new String(Integer.toString(num + 10000)).substring(1)的方法就会有问题。 - Felype
20个回答

1

您需要使用 Formatter,以下代码使用 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));

输出:0001

1
使用DecimalFormat类,如下所示:

使用DecimalFormat类,如下所示:

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

输出 : 0000811


4
在这种情况下,输出为0811。 - OJVM

0
你可以像这样给字符串添加前导0。定义一个字符串,该字符串将是您想要的字符串的最大长度。在我的情况下,我需要一个只有9个字符长的字符串。
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);

输出:000602939


0
在 Kotlin 中,您可以使用 format() 函数。
val minutes = 5
val strMinutes = "%02d".format(minutes)

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

输出:05


0

请检查我的代码,它适用于整数和字符串。

假设我们的第一个数字是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);

(new char[diff]) why - Isaac
replace("\0", "0")是什么意思? - Isaac
@Isaac - 首先,我创建了一个 char 数组,然后使用该 char 数组创建了一个字符串。接下来,我用 "0"(这是我们在此处需要的填充字符)替换了空字符(这是 char 类型的默认值)。 - Fathah Rehman P

0
如果您使用的是Java 15及以上版本,
var minutes = 5
var strMinutes = "%02d".formatted(minutes)

在这里,2是您想要显示的总位数(包括零)。

Output: 05

这个使用了字符串的实例方法中的formatted方法,它与静态的String.format(str,x,y,z)方法的功能相同。

-1

使用这个简单的扩展函数

fun Int.padZero(): String {
    return if (this < 10) {
        "0$this"
    } else {
        this.toString()
    }
}

-2

对于 Kotlin

fun Calendar.getFullDate(): String {
    val mYear = "${this.get(Calendar.YEAR)}-"
    val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
        "0${this.get(Calendar.MONTH) + 1}-"
    } else {
        "${this.get(Calendar.MONTH)+ 1}-"
    }
    val mDate = if (this.get(Calendar.DAY_OF_MONTH)  < 10) {
        "0${this.get(Calendar.DAY_OF_MONTH)}"
    } else {
        "${this.get(Calendar.DAY_OF_MONTH)}"
    }
    return mYear + mMonth + mDate
}

并将其用作

val date: String = calendar.getFullDate()


-3

无需安装任何包:

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

这将把字符串填充到三个字符,并且很容易添加更多部分以达到四或五个字符。我知道这在任何情况下都不是完美的解决方案(特别是如果您想要一个大的填充字符串),但我喜欢它。


2
嗯...我喜欢它。 - Kartik Chugh

-4

这里有另一种在整数左侧填充零的方法。您可以根据需要增加零的数量。已添加检查以在负数或大于或等于配置的零的值的情况下返回相同的值。您可以根据需要进一步修改。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接