I have an integer 100, how do I format it to look like 00000100 (always 8 digits long)?
8 Answers
Try this:
String formattedNumber = String.format("%08d", number); 1 Comment
Tomasz Gutkowski
Each time it is called a new formater instance is created. So I have to admit that with large amounts of data it can cause big memory problems.
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); } }); } } 3 Comments
João Silva
+1 for the creative, though slow solution :-).
polygenelubricants
Doesn't work with negatives, though.
Peter Lawrey
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.