你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
当前回答
找到这个例子…将测试……
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 paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
这将把字符串填充到三个字符,并且很容易为四个或五个字符添加更多的部分。我知道这在任何方面都不是完美的解决方案(特别是如果你想要一个大的填充字符串),但我喜欢它。
你可以像这样给字符串加上前导0。定义一个字符串,该字符串将是所需字符串的最大长度。在我的情况下,我需要一个字符串,将只有9字符长。
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
输出:000602939
如果你出于任何原因使用1.5之前的Java,那么可以尝试使用Apache Commons Lang方法
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
下面是如何不使用DecimalFormat格式化字符串的方法。
字符串。格式(“% 2 d”,9)
09
字符串。格式(“% d 03”,19)
019
字符串。格式(“% 04 d”,119年)
0119
您需要使用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