你如何在java中转换为字符串时留下一个零填充int ?

我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。


当前回答

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

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

其他回答

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

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

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

对于我的目的,我认为这两个都可以。格式更好,更简洁。

下面是如何不使用DecimalFormat格式化字符串的方法。

字符串。格式(“% 2 d”,9)

09

字符串。格式(“% d 03”,19)

019

字符串。格式(“% 04 d”,119年)

0119

不需要软件包:

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

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

使用这个简单的扩展函数

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