1

How do I fill in the space of the first column in the following code with 0's?

for(int i = 0; i < 10; i++) {
    System.out.printf("%-3.0f  %-1s%8.2f%1s %8.2f\n", (double)i, "[", 10d, "]", 10000d);
}

Output:

0    [   10.00] 10000.00
1    [   10.00] 10000.00
...

Ouput I want

000  [   10.00] 10000.00
001  [   10.00] 10000.00
...

3 Answers 3

3

Put a zero in front of the print format:

System.out.printf("%03.0f ...");
// -----------------^
Sign up to request clarification or add additional context in comments.

3 Comments

Great, that worked! Thanks! Also is there another way to use an integer in the formatting? it doesn't like %03.0i... I am just converting the int to a double right now, but that doesn't seem like the best way.
@Xzar: use %03d for integer types.
I get an IllegalFormatPrecisionException: 0 when using d
0
  for(int i = 0; i < 10; i++) {
       System.out.printf("%-3.0f  %-1s%08.2f%1s %08.2f\n", (double)i, "[", 10d, "]", 10000d);
  }

See the 0 before the 8.

1 Comment

Is there a way to format integers for the first column? I want something like %03.0i if thats possible
0
    for(int i = 0; i < 10; i++) {
        System.out.printf("%03d  %-1s%8.2f%1s %8.2f\n", (int)i, "[", 10d, "]", 10000d);

2 Comments

When will it throw that exception?
you don't need that part, I just take the top part from some other project to test the code..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.