Reputation: 522
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!
Upvotes: 2
Views: 242
Reputation: 4213
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);
Upvotes: 1