Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set width AND pad integer witdth String Formatter in Java

Given I have the following integers:

1, 10, 100

I want to pad them with zeroes to have exactly 3 digits:

001
010
100

and I want to print them prefixed by 10 spaces:

      001 //assume 10 spaces from the beginning of the line 
      010
      100

I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.

Below are 2 expressions that I created that accomplish each one of these conditions:

    @Test
    public void test1() {

        String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
        int[] nums = {1, 10, 100};

        for (int i = 0; i < 3; i++) {

            String s = langs[i];
            int n = nums[i];

            System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
        }

    }

According to documentation the formatter string has the below form:

%[argument_index$][flags][width][.precision]conversion

but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".

How can this be rewritten to accomplish the above mentioned conditions?

NOTE:

My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:

System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);

EDIT:

My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:

textX       001
textXXX     010
textXX      100

So that the spacing is variable.

like image 655
Eugene S Avatar asked Apr 08 '26 22:04

Eugene S


1 Answers

If the two only criterias are the padding of 10 Spaces and zero-padding of the numbers:

final String str = String.format("%10s%03d", " ", 2);

Edit after update from OP:

 System.out.printf("%-10s%03d", "abc", 2);

How it Works:

We need two arguments for Our pattern, one for the String of length 10, and one for the integer.

%10s is a pattern for a String of length 10. In order to left align it, we add the -: %-10s. The second argument is the integer of length 3 that we want to left pad With zero: %03d.

If we dont want to rearrange or reuse an argument for multiple format specifiers, just pass the arguments in the order specified in the pattern.

like image 131
msfoster Avatar answered Apr 10 '26 11:04

msfoster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!