0

I am trying to show number with percentage sign left justified along with other integer and string. For that I am using string format in java. I almost got it but stuck when ten's digit move to hundred digit. For example:

public class Test1 {

public static void main(String args[]){
int per1= 100,g1=3;
String name1="AAA PPPP";
int per2= 55,g2=4;
String name2="BBB QQQ";
int per3= 24,g3=7;
String name3="CCC RRRRR";

System.out.println(String.format("%-3d%% | %02d strike | %s",per1,g1,name1));
System.out.println(String.format("%-3d%% | %02d strike | %s",per2,g2,name2));
System.out.println(String.format("%-3d%% | %02d strike | %s",per3,g3,name3));

}

}

Currently, the output I m getting is this

100% | 03 strike | AAA PPPP
55 % | 04 strike | BBB QQQ
24 % | 07 strike | CCC RRRRR

but expected is

100% | 03 strike | AAA PPPP
55%  | 04 strike | BBB QQQ
24%  | 07 strike | CCC RRRRR

I m badly stuck now. I know its very tricky but still m struggling to get answer. Please help people.

1 Answers1

0

It can be an overkill but it works:

public class Test1 {

    public static void main(String args[]){

        int per1= 100, g1=3;

        String name1="AAA PPPP";

        int per2= 55, g2=4;

        String name2="BBB QQQ";

        int per3= 24, g3=7;

        String name3="CCC RRRRR";

        String space = "";

        System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per1).length()) + "s| %02d strike | %s", per1, space, g1, name1));
        System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per2).length()) + "s| %02d strike | %s", per2, space, g2, name2));
        System.out.println(String.format("%d%%%-" + (4 - String.valueOf(per3).length()) + "s| %02d strike | %s", per3, space, g3, name3));
    }
}

Output:

100% | 03 strike | AAA PPPP
55%  | 04 strike | BBB QQQ
24%  | 07 strike | CCC RRRRR
rjsperes
  • 65
  • 1
  • 8