你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
当前回答
如果性能在您的情况下很重要,您可以自己做,与String相比开销更少。格式功能:
/**
* @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
字符串。格式:38134毫秒
其他回答
假设你想把11打印成011
您可以使用格式化程序:“%03d”。
你可以像这样使用这个格式化器:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
另外,一些java方法直接支持这些格式化器:
System.out.printf("%03d", a);
你可以像这样给字符串加上前导0。定义一个字符串,该字符串将是所需字符串的最大长度。在我的情况下,我需要一个字符串,将只有9字符长。
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
输出:000602939
找到这个例子…将测试……
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的一部分。
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()