你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
当前回答
试试这个:
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
其他回答
找到这个例子…将测试……
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);
对于我的目的,我认为这两个都可以。格式更好,更简洁。
使用java.lang.String.format(String,Object…)
String.format("%05d", yournumber);
对于长度为5的零填充。对于十六进制输出,将d替换为“%05x”中的x。
完整的格式化选项被记录为java.util.Formatter的一部分。
如果你出于任何原因使用1.5之前的Java,那么可以尝试使用Apache Commons Lang方法
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
假设你想把11打印成011
您可以使用格式化程序:“%03d”。
你可以像这样使用这个格式化器:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
另外,一些java方法直接支持这些格式化器:
System.out.printf("%03d", a);
使用这个简单的扩展函数
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}