У меня есть целое число 100
, как его форматировать, чтобы выглядеть как 00000100
(всегда 8 цифр)?
Как добавить оставшиеся нули в число в Java?
Ответ 1
Попробуйте следующее:
String formattedNumber = String.format("%08d", number);
Ответ 2
Вы также можете использовать класс DecimalFormat
, например:
NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100
Ответ 3
Еще один способ.;)
int x = ...
String text = (""+(500000000 + x)).substring(1);
-1 = > 99999999 (nines дополнение)
import java.util.concurrent.Callable;
/* Prints.
String.format("%08d"): Time per call 3822
(""+(500000000+x)).substring(1): Time per call 593
Space holder: Time per call 730
*/
public class StringTimer {
public static void time(String description, Callable<String> test) {
try {
// warmup
for(int i=0;i<10*1000;i++)
test.call();
long start = System.nanoTime();
for(int i=0;i<100*1000;i++)
test.call();
long time = System.nanoTime() - start;
System.out.printf("%s: Time per call %d%n", description, time/100/1000);
} catch (Exception e) {
System.out.println(description+" failed");
e.printStackTrace();
}
}
public static void main(String... args) {
time("String.format(\"%08d\")", new Callable<String>() {
int i =0;
public String call() throws Exception {
return String.format("%08d", i++);
}
});
time("(\"\"+(500000000+x)).substring(1)", new Callable<String>() {
int i =0;
public String call() throws Exception {
return (""+(500000000+(i++))).substring(1);
}
});
time("Space holder", new Callable<String>() {
int i =0;
public String call() throws Exception {
String spaceHolder = "00000000";
String intString = String.valueOf(i++);
return spaceHolder.substring(intString.length()).concat(intString);
}
});
}
}
Ответ 4
String.format
используется строка формата, которая описывается здесь
Ответ 5
Если Google Guava является опцией:
String output = Strings.padStart("" + 100, 8, '0');
Альтернативно Apache Commons Lang:
String output = StringUtils.leftPad("" + 100, 8, "0");
Ответ 6
Если вам просто нужно распечатать его, это более короткая версия:
System.out.printf("%08d\n", number);
Ответ 7
Это также работает:
int i = 53;
String spaceHolder = "00000000";
String intString = String.valueOf(i);
String string = spaceHolder.substring(intString.lenght()).contract(intString);
Но другие примеры намного проще.
Ответ 8
Если вам нужно проанализировать эту строку и или поддержать i18n, рассмотрим возможность расширения
java.text.Format
объект. Используйте другие ответы, чтобы помочь вам получить формат.