2

I'm trying to format a string using Java's String.format. I need to create a string like this: "<padding spaces> int1 / int2".

Right now I have the following format: " %1$d/%2$d10" or "%1$d10/%2$" (or just "%1$d/%2$d", without the width setting) but this is not working correctly. I want to have the string aligned to the right, with empty spaces as padding for a total width of 10.

I'm using "%1$10.1f" elsewhere in my code, for a single float. The double integers need to be padded to the same width.

I have googled my brains out, but am unable to find a way to pad the total string instead of the two individual integers. Help would be appreciated!

1
  • Pardon my mobile formatting Commented Jan 16, 2017 at 21:41

1 Answer 1

1

Create the double integer string first using:

int one = 1;
int two = 2;
String dints = String.format("%d / %d", one, two);

Then format the string dints with a width of 10:

String whatYouWant = String.format("%10s", dints);

Printing whatYouWant should output:

     1 / 2

You can also do it in one call, at the cost of readability, for instance:

String whatYouWant = String.format("%10s", String.format("%d / %d", one, two));

Or shorter:

String whatYouWant = String.format("%10s", one + " / " + two);
Sign up to request clarification or add additional context in comments.

3 Comments

So there is no way to do it in one call? Also, I need to use a padding of 9 in the second step for the string to have the same width as the float version. Can you explain why? Thanks a lot!
I updated my answer to address your first question. I'm not exactly sure why you have to use a padding of 9, perhaps you have a space in front of %10s whereas I do not. So your format string is " %10s" whereas mine is "%10s".
The bug was indeed somewhere else. Code is working fine

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.