I have an integer 100
, how do I format it to look like 00000100
(always 8 digits long)?
views:
190answers:
7
+15
A:
Try this:
String formattedNumber = String.format("%08d", number);
Andrew Hare
2010-04-24 15:56:01
+6
A:
You can also use the class DecimalFormat
, like so:
NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100
JG
2010-04-24 16:03:55
A:
This also works:
int i = 53;
String spaceHolder = "00000000";
String intString = String.valueOf(i);
String string = spaceHolder.substring(intString.lenght()).contract(intString);
But the other examples are much easier.
Martijn Courteaux
2010-04-24 20:32:27
+1
A:
Yet another way. ;)
int x = ...
String text = (""+(500000000 + x)).substring(1);
-1 => 99999999 (nines complement)
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);
}
});
}
}
Peter Lawrey
2010-04-24 20:50:34
+1 for the creative, though slow solution :-).
JG
2010-04-24 22:29:59
Doesn't work with negatives, though.
polygenelubricants
2010-04-25 05:53:16
You might find it not as slow as other solutions, and the behaviour isn't defined for negatives. Just like the other solutions, there will be a non DDDDDDDD, where D is a digit, output for negative numbers.
Peter Lawrey
2010-04-25 12:00:06
A:
If you need to parse this string and or support i18n consider extending the
java.text.Format
object. Use the other answers to help you get the format.
Adam Gent
2010-04-24 20:58:26
A:
If you just need to print it out, this is a shorter version:
System.out.printf("%08d\n", number);
tulskiy
2010-04-25 05:51:29